Home > Net >  How to specify certain labels on matplotlib legend
How to specify certain labels on matplotlib legend

Time:03-05

I try to produce the following plot, but the legend doesn't look very good. I want years to be integer number (not decimals) and space in periods like 2000, 2005, 2010, 2015, 2020 in the colorbar. Also legend title "Years" should be on top of the legend (not in the middle color bar) with fontsize=14. Hope someone can help.

import pandas as pd
import random
import matplotlib.pyplot as plt
df=pd.read_csv(r"https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/data.csv")
years=[i for i in range(2000,2022)]
df["Year"]=[random.choice(years) for i in range(len(df))]
fig, ax=plt.subplots(figsize=(15,8))
point=plt.scatter(df.Extent_km2/1000, df.Resolution_m, c=df.Year)
plt.xticks(fontsize=13) 
plt.yticks(fontsize=13)
ax.set_xlabel(r"Spatial extent (1000 $\rmkm^2$)", fontsize=15)
ax.set_ylabel("Spatial resolution (m)", fontsize=15) 
fig.colorbar(point)
plt.show()

CodePudding user response:

To change your colorbar ticks, you can set customized ticks with cb=plt.colorbar(points,ticks=np.arange(2000,2025,5)). To place, the title of your colorbar at the top, you can use: cb.ax.set_title('Years',fontsize=14). Overall, the code looks like that:

import pandas as pd
import random
import matplotlib.pyplot as plt
import numpy as np

df=pd.read_csv(r"https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/data.csv")
years=[i for i in range(2000,2022)]

df["Year"]=[random.choice(years) for i in range(len(df))]
fig, ax=plt.subplots(figsize=(15,8))
points=ax.scatter(df.Extent_km2/1000, df.Resolution_m, c=df.Year)

ax.tick_params(axis='both', which='major', labelsize=13)
ax.set_xlabel(r"Spatial extent (1000 $\rmkm^2$)", fontsize=15)
ax.set_ylabel("Spatial resolution (m)", fontsize=15) 

#setting up colorbar with customized ticks
cb=plt.colorbar(points,ticks=np.arange(2000,2025,5))

#setting up title
cb.ax.set_title('Years',fontsize=14)
plt.show()

And the output gives:

enter image description here

  • Related