【问题标题】:Show first and last label in pandas plot在熊猫图中显示第一个和最后一个标签
【发布时间】:2021-02-11 03:53:35
【问题描述】:

我有一个包含 361 列的 DataFrame。我想绘制它,但只显示图例中的第一列和最后一列。例如:

d = {'col1':[1,2],'col2':[3,4],'col3':[5,6],'col4':[7,8]}
df = pd.DataFrame(data=d)

如果我通过df.plot() 绘制所有图例,将显示所有图例,但我只希望我的图例中的'col1''col4' 具有正确的颜色代码(我正在使用颜色图)和图例标题。

这样做的一种方法是通过 matplotlib 单独绘制每一列而不使用图例,然后再绘制两个只有标签的空图(下面的示例),但我想知道是否有直接的方法来使用 pandas。

for columns in df:
    plt.plot(df[columns])
plt.plot([],[],label=df.columns[0])
plt.plot([],[],label=df.columns[-1])
plt.legend()
plt.show()

【问题讨论】:

    标签: python pandas legend


    【解决方案1】:

    让我们尝试从轴中提取处理程序/标签并定义新的图例:

    ax = df.plot()
    handlers, labels = ax.get_legend_handles_labels()
    new_handlers, new_labels = [], []
    
    for h,l in zip(handlers, labels):
        if l in ['col1','col4']:
            new_handlers.append(h)
            new_labels.append(l)
            
    ax.legend(new_handlers, new_labels)
    

    输出:

    【讨论】:

    • 嗯,它确实有效,但我要求更直接的方式,即没有循环。
    【解决方案2】:

    您可以尝试将您的 df 拆分为两个 df,第二个将仅包含感兴趣的列,然后绘制两个 df,仅显示第二个图例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 2013-05-21
      • 2023-03-13
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多