
In this post, you will learn how to add Titles, Axis Labels and Legends in your matplotlib plot.
Add Title –
To add title in matplotlib, we use plt.title() or ax.set_title()
Let’s read a dataset to work with.
import pandas as pd
url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/batting.csv"
df = pd.read_csv(url)
df.head()

Now, let’s create a scatter plot and add a title to it.
# add a Title to the plot
plt.figure(figsize=(10, 8))
plt.scatter(x=df['SR'], y=df['Runs'], color='seagreen')
plt.title('Runs vs Strike Rate')
plt.show()

ax.set_title() is used for adding title to the object oriented interface plots. For more information read this post – Matlab Style interface vs Object oriented interface
fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(x=df['SR'], y=df['Runs'], color='seagreen')
ax.set_title('Runs vs Strike Rate')
plt.show()

Add Axis Labels –
To add x axis labels, we use plt.xlabel() or ax.set_xlabel(). And to add y labels we use plt.ylabel() or ax.set_ylabel()
plt.figure(figsize=(10, 8))
plt.scatter(x=df['SR'], y=df['Runs'], color='seagreen')
plt.xlabel('Strike Rate')
plt.ylabel('Runs')
plt.title('Runs vs Strike Rate')
plt.show()

Add x-axis and y-axis label in object oriented interface
fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(x=df['SR'], y=df['Runs'], color='seagreen')
ax.set_title('Runs vs Strike Rate')
ax.set_xlabel('Strike Rate')
ax.set_ylabel('Runs')
plt.show()

If you look at the figure above, you can see that axis labels as well as the title are very small. We can make them bigger using the fontsize parameter.
fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(x=df['SR'], y=df['Runs'], color='seagreen')
ax.set_title('Runs vs Strike Rate', fontsize=20)
ax.set_xlabel('Strike Rate', fontsize=18)
ax.set_ylabel('Runs', fontsize=18)
plt.show()

Add Legend –
To add legends in matplotlib, we use the plt.legend() or ax.legend() . Note to make the legends visible to also need to add the labels parameter in the scatter plot.
indian = df[df['Nationality']=='Indian']
overseas = df[df['Nationality']=='Overseas']
plt.figure(figsize=(10, 8))
plt.scatter(x=indian['SR'], y=indian['Runs'],
label='Indian', color='seagreen')
plt.scatter(x=overseas['SR'], y=overseas['Runs'],
label='Overseas', color='crimson')
plt.xlabel("Strike Rate", fontsize=18)
plt.ylabel("Runs", fontsize=18)
plt.title("Runs vs Strike Rate", fontsize=20)
plt.legend()
plt.show()

indian = df[df['Nationality']=='Indian']
overseas = df[df['Nationality']=='Overseas']
fig, ax = plt.subplots(figsize=(10, 8))
ax.scatter(x=indian['SR'], y=indian['Runs'], label='Indian', color='seagreen')
ax.scatter(x=overseas['SR'], y=overseas['Runs'], label='overseas', color='crimson')
ax.set_title('Runs vs Strike Rate', fontsize=20)
ax.set_xlabel('Strike Rate', fontsize=18)
ax.set_ylabel('Runs', fontsize=18)
ax.legend()
plt.show()
