【问题标题】:bar chart legend based on coloring of bars by group not value条形图图例基于按组而不是值对条形着色
【发布时间】:2020-05-15 08:30:56
【问题描述】:

我已经按照here 的描述创建了一个条形图,其中我有多个变量(在“值”列中表示)并且它们属于重复组。我已经根据他们的组成员对条形图进行了着色。

我想创建一个最终等同于颜色字典的图例,显示与给定组成员对应的颜色。

代码在这里:

d = {'value': [1, 2, 4, 5, 7 ,10], 'group': [1, 2, 3, 2, 2, 3]}
df = pd.DataFrame(data=d)
colors = {1: 'r', 2: 'b', 3: 'g'}
df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])
plt.legend(df['group'])

这样,我只得到一个颜色为 (1) 而不是 (1, 2, 3) 的图例。

谢谢!

【问题讨论】:

    标签: python pandas matplotlib bar-chart


    【解决方案1】:

    你可以使用sns:

    sns.barplot(data=df, x=df.index, y='value', 
                hue='group', palette=colors, dodge=False)
    

    输出:

    【讨论】:

      【解决方案2】:

      使用 pandas,您可以按如下方式创建 your own legend

      from matplotlib import pyplot as plt
      from matplotlib import patches as mpatches
      import pandas as pd
      
      d = {'value': [1, 2, 4, 5, 7 ,10], 'group': [1, 2, 3, 2, 2, 3]}
      df = pd.DataFrame(data=d)
      colors = {1: 'r', 2: 'b', 3: 'g'}
      df['value'].plot(kind='bar', color=[colors[i] for i in df['group']])
      
      handles = [mpatches.Patch(color=colors[i]) for i in colors]
      labels = [f'group {i}' for i in colors]
      plt.legend(handles, labels)
      
      plt.show()
      

      【讨论】:

      • 或者只是 plt.legend(*zip(*[(plt.Rectangle((0,0), 1,1, color=c), f"group {i}") for i,c in colors.items()])) 在一行中。
      猜你喜欢
      • 1970-01-01
      • 2011-10-17
      • 2020-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多