当我使用 matplotlibs 命令时,我能够获得非常漂亮的彩色条形图。这非常有用,它使用了一些着色命令,例如
for box in bp['boxes']:
# change outline color
box.set( color='#7570b3', linewidth=2)
# change fill color
box.set( facecolor = '#1b9e77' )
但是,使用这些箱线图命令的问题,数据应该已经按照您在 x 轴上的需要进行分组。我关于 S.O. 的最后一个问题是关于这一点的,正如回复中所建议的,我可以使用
df.boxplot('data1',by='data2')
这对我来说非常有用,因为我可以按原样使用我的数据。但是,我不能在这里使用上面的一些着色选项。事实上,参数 color
也不被接受为参数,如以下几个示例所示
df.plot(kind='box',color='red')
但我仍然更喜欢使用 df.boxplot
命令(可能需要了解有关其他选项的更多信息(。
显然,我是 python 的新手,甚至对绘图工具也很新,所以我不了解这些选项中的每一个是如何深入工作的,但想深入了解制作条形图并为其添加颜色的最快方法是什么。
所以我的问题是,如果我使用df.boxplot
,如何向我的箱线图添加颜色
编辑:添加工作示例以显示我正在寻找的内容
如果我有这样的数据帧
import numpy as np
import pandas as pd
import matplotlib.pylab as plt
df=pd.DataFrame(np.random.rand(10,2),columns=['data1','data2'])
df['group']=['A','B','C','A','B','C','A','B','C','A']
我正在使用以下命令绘制一个箱形图,其中数据按列group
分组,我想在其中查看"data1"列的分布。
plt.figure(3)
df.boxplot(column='data1',by='group')
如何为其添加颜色?
如果我使用此命令,我知道如何添加颜色
plt.figure(1)
data2plot=[df['data1'],df['data2']]
plt.boxplot(data2plot)
这不会给出我想要的情节并获得我想要的情节,我真的必须使用以下代码:
grA=[val for ind, val in zip(df['group'],df['data1']) if ind=='A']
grB=[val for ind, val in zip(df['group'],df['data1']) if ind=='B']
grC=[val for ind, val in zip(df['group'],df['data1']) if ind=='C']
plt.figure(2)
data2plot_new=[grA,grB,grC]
plt.boxplot(data2plot_new)
如果我使用上述方法,我知道如何添加颜色,但它看起来效率不高。
我知道在哪里可以使用"颜色"参数的另一个选项是这个
df.plot(data2plot,kind='box',color='red')
但即使在这里,我也需要进行一些数据转换才能获得我想要的情节。
所以问题又是,如果我使用第一个选项,如何更改颜色、厚度等绘图属性。
我希望这是清楚的。
@Goyo更完整的答案应该是
box1=df.boxplot('data1',by='group',return_type='dict',patch_artist=False)
[x.set(color='g',linewidth=2) for x in box1['data1']['boxes']]
[x.set(facecolor='r') for x in box1['data1']['boxes']]
(@Goyo,虽然你的回答肯定帮助我挖掘了更多信息,但有趣的是,你抱怨我的问题不完整,然后发布了一个不完整的答案!
我将其作为答案发布,因为它符合我当前的目的。
使用 return_type='dict'
。
df.boxplot(column='data1',by='group', return_type='dict')
OrderedDict([('data1',
{'boxes': [<matplotlib.lines.Line2D at 0x9986e70>,
<matplotlib.lines.Line2D at 0x999e2f0>,
<matplotlib.lines.Line2D at 0x99ab9d0>],
'caps': [<matplotlib.lines.Line2D at 0x99926b0>,
<matplotlib.lines.Line2D at 0x99929f0>,
<matplotlib.lines.Line2D at 0x999ed90>,
<matplotlib.lines.Line2D at 0x99ab0f0>,
<matplotlib.lines.Line2D at 0x9a6d470>,
<matplotlib.lines.Line2D at 0x9a6d7b0>],
'fliers': [<matplotlib.lines.Line2D at 0x9992ff0>,
<matplotlib.lines.Line2D at 0x99ab770>,
<matplotlib.lines.Line2D at 0x9a6de30>],
'means': [],
'medians': [<matplotlib.lines.Line2D at 0x9992d10>,
<matplotlib.lines.Line2D at 0x99ab410>,
<matplotlib.lines.Line2D at 0x9a6dad0>],
'whiskers': [<matplotlib.lines.Line2D at 0x9986fd0>,
<matplotlib.lines.Line2D at 0x9992370>,
<matplotlib.lines.Line2D at 0x999e710>,
<matplotlib.lines.Line2D at 0x999ea50>,
<matplotlib.lines.Line2D at 0x99abdd0>,
<matplotlib.lines.Line2D at 0x9a6d130>]})])