【问题标题】:Adding a legend to a Pandas DataFrame boxplot向 Pandas DataFrame 箱线图添加图例
【发布时间】:2018-04-08 11:17:40
【问题描述】:

我正在同一轴上绘制一系列箱线图,并希望添加一个图例来识别它们。 非常简化,我的脚本如下所示:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df={}
bp={}
positions = [1,2,3,4]
df[0]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
df[1]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
colour=['red','blue']
fig, ax = plt.subplots()
for i in [0,1]:
    bp[i] = df[i].plot.box(ax=ax,
                          positions = positions,
                          color={'whiskers': colour[i],
                                 'caps': colour[i],
                                 'medians': colour[i],
                                 'boxes': colour[i]}
                          )
plt.legend([bp[i] for i in [0,1]], ['first plot', 'second plot'])
fig.show()

情节很好,但未绘制图例,我收到此警告

    UserWarning: Legend does not support <matplotlib.axes._subplots.AxesSubplot object at 0x000000000A7830F0> instances.
A proxy artist may be used instead.

(我之前在散点图中添加图例时曾收到此警告,但图例仍被绘制,所以我可以忽略它。)

Here is a link to a description of proxy artists,但不清楚如何将其应用于我的脚本。有什么建议吗?

【问题讨论】:

    标签: python pandas matplotlib legend boxplot


    【解决方案1】:

    'pandas' 绘图返回不能用于生成图例的 AxesSubplot 对象。您必须使用 proxy artist 生成您自己的图例。我修改了你的代码:

    import pandas as pd
    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.patches as mpatches
    df={}
    bp={}
    positions = [1,2,3,4]
    df[0]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
    df[1]= pd.DataFrame (np.random.rand(4,4),columns =['A','B','C','D'])
    colour=['red','blue']
    fig, ax = plt.subplots()
    for i in [0,1]:
        bp[i] = df[i].plot.box(ax=ax,
                              positions = positions,
                              color={'whiskers': colour[i],
                                     'caps': colour[i],
                                     'medians': colour[i],
                                     'boxes': colour[i]}
                              )
    
    red_patch = mpatches.Patch(color='red', label='The red data')
    blue_patch = mpatches.Patch(color='blue', label='The blue data')
    plt.legend(handles=[red_patch, blue_patch])
    
    plt.show()
    

    结果如下:

    【讨论】:

      猜你喜欢
      • 2020-09-16
      • 2020-08-08
      • 2021-10-28
      • 2017-08-03
      • 2016-01-26
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多