向 Pandas DataFrame 箱线图添加图例
Posted
技术标签:
【中文标题】向 Pandas DataFrame 箱线图添加图例【英文标题】:Adding a legend to a Pandas DataFrame boxplot 【发布时间】: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
,但不清楚如何将其应用于我的脚本。有什么建议吗?
【问题讨论】:
【参考方案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()
结果如下:
【讨论】:
以上是关于向 Pandas DataFrame 箱线图添加图例的主要内容,如果未能解决你的问题,请参考以下文章
将分割图(点图)添加到分组箱线图 - Pandas 和 Seaborn