【问题标题】:Seaborne Linechart Style Causing Duplicate Legend EntriesSeaborn 折线图样式导致重复的图例条目
【发布时间】:2021-04-28 04:22:06
【问题描述】:

我正在使用 seaborn 来绘制使用本福德定律的一些工作的结果。该图有两个轴:一个表示输入数据中数字的相对频率的条形图,一个表示本福德定律的预期频率的折线图。

this question 一样,我使用style=True 选项来控制线条的样式。不幸的是,这会导致我的图例中出现重复条目​​,我似乎无法将其删除。如何更正图例中的重复条目?

当前代码:

def plot(inputdata, digits, y_col_actual, y_col_expected):

    plt.rcParams['patch.force_edgecolor']=True

    ax1 = sns.barplot(
        data=inputdata,
        x = digits,
        y = y_col_actual,
        color = '#B2E8C2',
        label='Actual Data'
        )
    ax1.set(ylabel='Relative Frequency')

    ax2 = sns.lineplot(
        data=inputdata,
        x = digits,
        y = y_col_expected,
        ax = ax1,
        zorder = 5,
        color = 'black',
        style=True,
        dashes=[(2,2)],
        markers=True,
        label='Benfords Law',
        )
    
    plt.show()

以及由此产生的情节:

【问题讨论】:

  • 你对风格做了什么尝试? Style 应该是 DataFrame 中列的名称,不是布尔选项。这就是它出现在传说中的原因。可能您要设置的是dashes=Truelinestyle='--'
  • @jjsantoso 需要设置样式才能使用破折号。只有一行(没有要区分的类别),所以我不想提供列名 - 所以 True 是一个有效的替代方案。将破折号设置为 True 实际上不会产生任何虚线。

标签: python python-3.x matplotlib seaborn visualization


【解决方案1】:

不是一个很好的解决方案,但是当我将它附加到 plot 函数的末尾时,这对我有用:

handles, labels = ax2.get_legend_handles_labels()
labels[1] = "_True"
ax2.legend(handles, labels)

这是因为matplotlib 会忽略任何以下划线开头的标签。由于在您的情况下,labels[1] = "True" 是违规者,因此它已被覆盖为 "_True"

【讨论】:

  • 完美运行!谢谢你的解释。这是一个聪明的把戏。
【解决方案2】:

legend=False放入lineplot,然后自己添加图例:

ax = sns.lineplot(
    x=[1, 2, 3], y=[1, 2, 3],
    style=True, dashes=[(2, 2)],
    label="Test", legend=False
)
ax.legend()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多