matplotlib 在Python中添加分组的箱线图图例

w6lpcovy  于 2023-06-23  发布在  Python
关注(0)|答案(1)|浏览(156)

我有两个 Dataframe (df1和df2),每个都有一个形状(60,20)。我将它们水平组合(即60,40),并使用箱形图绘制40列。现在我想添加图例(只有两个图例,因为df1和df2的所有20列都被分组并被视为一种图例)。我已经搜索并查看了几个帖子,但没有类似于我的问题。我把我的代码和输出图如下。如图所示,我需要添加两个图例('A'表示所有红色箱线图,'B'表示所有金色箱线图)。

df_combined = pd.concat([df1, df2], axis=1)
fig, ax1 = plt.subplots(figsize=(10,6))
labels = ['1', '2', '3','4', '5', 
  '6','7','8','9','10','11','12','13','14','15','16','17','18','19','20',
      '21', '22', '23','24', '25', 
           '26','27','28','29','30','31','32','33','34','35','36','37','38','39','40']
 props = ax1.boxplot(df_combined ,
                 vert=True,  
                 patch_artist=True,  
                 labels=labels)
 ax1.yaxis.grid(True)
 plt.show()

ogsagwnx

ogsagwnx1#

你可以试试下面的…一旦你画出了箱线图,使用patch.set(facecolor=<...>)给予你想要的颜色。类似地,使用补丁和标签给予您需要的自定义ax1.legend()

## My random data
df1=pd.DataFrame(np.random.randint(25, 225, size=(60,20)))
df2=pd.DataFrame(np.random.randint(25, 225, size=(60,20)))

##Your code for creation of boxplot
df_combined = pd.concat([df1, df2], axis=1)
fig, ax1 = plt.subplots(figsize=(10,6))
props = ax1.boxplot(df_combined,
                 vert=True,  
                 patch_artist=True,  
                 labels=list(range(1,41)))  ## Note - use range as it is simpler/easier

## New code... for each patch (the box) in the boxplot, color ...
for i, patch in enumerate(props['boxes']):
    if i < 21:  ## First 20 as red
        patch.set(facecolor='red') 
    else:  ## Last 20 as golden
        patch.set(facecolor='goldenrod')
        
ax1.yaxis.grid(True)

##New code - For plotting legend, take first (red) box and first (golden) box, and the label names you want
ax1.legend([props["boxes"][0], props["boxes"][21]], ['Red-A', 'Golden-B'])
plt.show()

相关问题