【问题标题】:Matplotlib / Seaborn legend changes style upon adding labelsMatplotlib / Seaborn 图例在添加标签时改变样式
【发布时间】:2019-05-23 17:53:50
【问题描述】:

我正在使用 seaborn 绘制来自 pandas df 的一些数据。使用以下代码几乎可以很好地绘制所有内容:

import pandas as pd
import seaborn as sns

sns.set(style='whitegrid', palette='muted')

legend = ["Hue 1", "Hue 2"]
order = ["A", "B"]

ax = sns.violinplot(x=df.xaxis, y=df.yaxis, hue=df.hue,
                    split=True, order=order)
ax.set_ylim(0, 100)
ax.set(xlabel='X - axis', ylabel='Y - axis')
ax.legend(title='Legend', loc='upper left', labels=legend)
ax.set_title('My little plot')
plt.show()

添加labels= 后,图例中显示的“线型”就会发生变化。下面是一个截图。不幸的是,我的数据集太大而无法发布,所以我希望这已经足够了。

提前致谢。 BBQuercus :)

左边没有,右边有labels(R、C 是我数据中的值)。

【问题讨论】:

  • 也许您可以将在小提琴图中绘制的补丁的句柄传递给ax.legend 函数。您可以在ax.collections 下找到句柄

标签: python pandas matplotlib seaborn


【解决方案1】:

您可以尝试为您的图例绘制自定义补丁。我没有对此进行测试,但我认为它应该可以工作。

from matplotlib.patches import Patch
palette=sns.color_palette('muted')

bluepatch = Patch(
    facecolor=palette[0],edgecolor='k',label='Hue 1'
)
orangepatch = Patch(
    facecolor=palette[1],edgecolor='k',label='Hue 2'
)

ax.legend(
    labels=['Hue 1','Hue 2'], 
    handles=[bluepatch, orangepatch], 
    title='Legend', 
    loc='upper left'
)

【讨论】:

  • 工作。非常感谢!
猜你喜欢
  • 2020-09-16
  • 2020-12-13
  • 2021-04-10
  • 1970-01-01
  • 2021-06-25
  • 2018-05-18
  • 2014-06-22
  • 1970-01-01
  • 2020-09-10
相关资源
最近更新 更多