如何在 matplotlib 图例上指定某些标签
我尝试制作以下情节,但图例看起来不太好。我希望年份是整数(不是小数),并且颜色栏中的 2000、2005、2010、2015、2020 等期间的空格。此外,图例标题“Years”应位于图例顶部(而不是中间颜色栏),并带有 fontsize=14
。希望有人能帮忙。
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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要更改颜色条刻度,您可以使用
cb=plt.colorbar(points,ticks=np.arange(2000,2025,5))
设置自定义刻度。要将颜色栏的标题放置在顶部,您可以使用:cb.ax.set_title('Years',fontsize=14)
。总的来说,代码如下:
输出给出:
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:
And the output gives: