Matplotlib:在一行上显示多个标签
Posted
技术标签:
【中文标题】Matplotlib:在一行上显示多个标签【英文标题】:Matplotlib : display several labels on a single line 【发布时间】:2021-07-03 06:08:33 【问题描述】:我有一个 DF,就像这个:
DF=pd.DataFrame.from_dict("date":["2019-01-01","2019-01-02","2019-01-03","2019-01-04","2019-01-05","2019-01-06","2019-01-07","2019-01-08","2019-01-09","2019-01-10"],
"temperature":[9,7,5,14,17,18,16,13.5,19,21],
"shorter_opinion":["bad & very bad","bad & very bad","bad & very bad","not good not bad","good & very good", "good & very good", "good & very good","not good not bad","not good not bad","bad & very bad"])
为了用一种颜色为每个 DF["shorter_opinion"] 值可视化,我创建了一个字典,并显示如下:
colors="good & very good":"green","not good not bad":"yellow","bad & very bad":"red"
plt.figure()
plt.scatter(x = DF["date"], y = DF["temperature"], c=DF["shorter_opinion"].map(colors))
plt.xticks(DF["date"][::3])
plt.legend(loc="upper right")
plt.show()
我尝试使用 Serie.Unique() 在图例中显示此单打状态
plt.figure()
plt.scatter(x = DF["date"], y = DF["temperature"], c=DF["shorter_opinion"].map(colors), label=DF["shorter_opinion"].unique())
plt.xticks(DF["date"][::3])
plt.legend(loc="upper right")
plt.show()
但是得到了这张照片
如何修改此代码以使每个值都位于正确的颜色旁边?
【问题讨论】:
【参考方案1】:一种解决方案可能是使用补丁,如下所示:
plt.figure()
plt.scatter(x = DF["date"], y = DF["temperature"], c=DF["shorter_opinion"].map(colors), label=DF["shorter_opinion"].unique())
plt.xticks(DF["date"][::3])
patches = [ plt.plot([],[], marker="o", ms=10, ls="", mec=None, color=colors[i],
label=i)[0] for i in colors.keys() ]
plt.legend(colors.keys())
plt.show()
【讨论】:
以上是关于Matplotlib:在一行上显示多个标签的主要内容,如果未能解决你的问题,请参考以下文章
python使用matplotlib对比多个模型在测试集上的效果并可视化设置模型性能可视化结果柱状图(bar plot)标签的小数点位数(例如,强制柱状图标签0.7显示为两位小数0.70)
Python使用matplotlib函数subplot可视化多个不同颜色的折线图在折线图上为每个数据点添加数值标签