如何解决如何自定义seaborn.scatterplot图例?
我用海底图书馆绘制了一个散点图,我想更改图例文本,但不知道该怎么做。
示例: 以下是虹膜数据集,其中物种列按物种按0/1/2编码。
plt.figure(figsize=(8,8))
pl = sns.scatterplot(x='petal_length',y ='petal_width',hue='Species',data=data,s=40,palette='Set1',legend='full')
我想将图例文本从[0,1,2]更改为['setosa','versicolor','virginica']。 谁能帮忙。
解决方法
首先,Seaborn(和Matplotlib)通常会从您提供为hue
的数组的唯一值中选取要放入hue
的图例的标签。因此,作为第一步,请检查数据框中的列Species
是否实际包含值“ setosa”,“ versicolor”,“ virginica”。如果不是,一种解决方案是暂时将它们map
设为其他值,以进行绘制:
legend_map = {0: 'setosa',1: 'versicolor',2: 'virginica'}
plt.figure(figsize=(8,8))
ax = sns.scatterplot(x=data['petal_length'],y =data['petal_width'],hue=data['species'].map(legend_map),s=40,palette='Set1',legend='full')
plt.show()
或者,如果您想直接操作图信息而不是基础数据,则可以通过直接访问图例名称来完成:
plt.figure(figsize=(8,8))
ax = sns.scatterplot(x='petal_length',y ='petal_width',hue='species',data=data,legend='full')
l = ax.legend()
l.get_texts()[0].set_text('Species') # You can also change the legend title
l.get_texts()[1].set_text('Setosa')
l.get_texts()[2].set_text('Versicolor')
l.get_texts()[3].set_text('Virginica')
plt.show()
如果需要,此方法还可以更改图例标题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。