【问题标题】:Adding legend by list within subplot Matplotlib在子图 Matplotlib 中按列表添加图例
【发布时间】:2021-12-02 22:58:42
【问题描述】:

我想在一个图中绘制 2 个不同的图表。一张图只是一条线,因此标记图例没有问题。在 df_2_plot 中是提供的代码列表,因此图例中有更多行和更多代码。如果我这样标记它们,我只会在图例中多次收到列表,而不是每行的正确代码。

我尝试使用 for 循环,但找不到解决方案。

def func_plot_DataFrame(df_2_plot, legend_lst):
    
    
    y1 = df_2_plot
    y2 = df_infektionsgeschehen

    fig, ax1 = plt.subplots()

    ax2 = ax1.twinx()
    
    ax1.plot(y1, label = legend_lst)
    ax2.plot(y2, 'grey', linewidth=2, alpha=0.3, label = 'Neuinfektionen')


    plt.show()

【问题讨论】:

  • 您只需要ax = df_infektionsgeschehen.plot(figsize=(8, 6)),然后是df_2_plot.plot(color='gray', alpha=0.3, ax=ax, secondary_y=True)。仅当数据框中的列超过 3 列时,才在第一个图中使用 y=legend_list

标签: python list matplotlib legend subplot


【解决方案1】:

您需要使用ax1.legend 而不是直接在ax1.plot 中使用label 参数

ax1.legend(labels=legend_lst)

看看官方文档here

【讨论】:

    猜你喜欢
    • 2018-02-26
    • 1970-01-01
    • 2012-03-04
    • 2016-04-28
    • 2017-10-14
    • 2020-09-16
    • 2017-07-20
    • 1970-01-01
    • 2021-05-03
    相关资源
    最近更新 更多