我想用我的DataFrame绘制箱形图:
A B C
max 10 11 14
min 3 4 10
q1 5 6 12
q3 9 7 13
如何绘制具有这些固定值的箱形图?
答案 0 :(得分:0)
您可以基于Axes.bxp method在matplotlib中使用this helpful answer。输入是包含相关值的词典列表,但是中位数是这些词典中的必需键。由于您提供的数据不包括中位数,因此我在下面的代码中组成了中位数(但您需要根据实际数据进行计算)。
import matplotlib.pyplot as plt
import pandas as pd
# reproducing your data
df = pd.DataFrame({'A':[10,3,5,9],'B':[11,4,6,7],'C':[14,10,12,13]})
# add a row for median, you need median values!
sample_medians = {'A':7, 'B':6.5, 'C':12.5}
df = df.append(sample_medians, ignore_index=True)
df.index = ['max','min','q1','q3','med']
这是经过修改的df,其中包括中值:
>>> df
A B C
max 10.0 11.0 14.0
min 3.0 4.0 10.0
q1 5.0 6.0 12.0
q3 9.0 7.0 13.0
med 7.0 6.5 12.5
现在,我们将df转换为词典列表:
labels = list(df.columns)
# create dictionaries for each column as items of a list
bxp_stats = df.apply(lambda x: {'med':x.med, 'q1':x.q1, 'q3':x.q3, 'whislo':x['min'], 'whishi':x['max']}, axis=0).tolist()
# add the column names as labels to each dictionary entry
for index, item in enumerate(bxp_stats):
item.update({'label':labels[index]})
_, ax = plt.subplots()
ax.bxp(bxp_stats, showfliers=False);
plt.show()
不幸的是,中线是必填参数,因此必须为每个框指定。因此,我们只是使它尽可能薄以至于几乎看不见。
如果要以不同的规格绘制每个框,则它们必须位于不同的子图中。我知道这看起来是否很丑陋,所以您可以使用子图之间的间距,或者考虑删除一些y轴。
fig, axes = plt.subplots(nrows=1, ncols=3, sharey=True)
# specify list of background colors, median line colors same as background with as thin of a width as possible
colors = ['LightCoral', '#FEF1B5', '#EEAEEE']
medianprops = [dict(linewidth = 0.1, color='LightCoral'), dict(linewidth = 0.1, color='#FEF1B5'), dict(linewidth = 0.1, color='#EEAEEE')]
# create a list of boxplots of length 3
bplots = [axes[i].bxp([bxp_stats[i]], medianprops=medianprops[i], patch_artist=True, showfliers=False) for i in range(len(df.columns))]
# set each boxplot a different color
for i, bplot in enumerate(bplots):
for patch in bplot['boxes']:
patch.set_facecolor(colors[i])
plt.show()