更改pandas boxplot子图中单个盒子的颜色 [英] Change color of individual boxes in pandas boxplot subplots

查看:260
本文介绍了更改pandas boxplot子图中单个盒子的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是参考以下问题,其中讨论了用于调整子图的标题和布局的选项: 修改熊猫boxplot输出

This is in reference to the following question, wherein options for adjusting title and layout of subplots are discussed: modify pandas boxplot output

我的要求是更改每个子图中各个框的颜色(如下图所示):

My requirement is to change the colors of individual boxes in each subplot (as depicted below):

以下是共享链接上可用的代码,用于调整子图的标题和轴属性:

Following is the code available at the shared link for adjusting the title and axis properties of subplots:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])
df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4',     'model5', 'model6', 'model7'], 20))
bp = df.boxplot(by="models",layout=(4,1),figsize=(6,8))
[ax_tmp.set_xlabel('') for ax_tmp in np.asarray(bp).reshape(-1)]
fig = np.asarray(bp).reshape(-1)[0].get_figure()
fig.suptitle('New title here')
plt.show()

我尝试使用: ax.set_facecolor('color') 属性,但无法成功获得预期的结果.

I tried using the: ax.set_facecolor('color') property, but not successful in obtaining the desired result.

我也尝试访问bp ['boxes'],但显然不可用.我需要对存储在bp中的数据结构有所了解,以便访问子图中的各个框.

I tried accessing bp['boxes'] as well but apparently it is not available. I need some understanding of the structure of data stored in bp for accessing the individual boxes in the subplot.

向前看

P.S:我知道seaborn.但是目前需要了解并使用df.boxplot实施.谢谢

P.S: I am aware of seaborn. But need to understand and implement using df.boxplot currently. Thanks

推荐答案

要调整pandas.boxplot中框的颜色,必须稍微调整代码.首先,您必须告诉boxplot实际上用一种颜色填充框.您可以通过指定patch_artist = True来执行此操作,如此处所述.但是,您似乎无法指定颜色(默认为蓝色),如果我输入错了,请有人纠正我.这意味着您之后必须更改颜色.幸运的是,pandas.boxplot提供了一个简单的选项,通过指定return_type = 'both' 请参见此处以获取说明.您得到的是一个pandas.Series,其中的键根据您的DataFrame列和值组成的元组,这些元组包含在其上绘制箱线图的Axes实例以及词典中箱线图的实际元素.我认为代码是不言自明的:

To adjust the colours of your boxes in pandas.boxplot, you have to adjust your code slightly. First of all, you have to tell boxplot to actually fill the boxes with a colour. You do this by specifying patch_artist = True, as is documented here. However, it appears that you cannot specify a colour (default is blue) -- please anybody correct me if I'm wrong. This means you have to change the colour afterwards. Luckily pandas.boxplot offers an easy option to get the artists in the boxplot as return value by specifying return_type = 'both' see here for an explanation. What you get is a pandas.Series with keys according to your DataFrame columns and values that are tuples containing the Axes instances on which the boxplots are drawn and the actual elements of the boxplots in a dictionary. I think the code is pretty self-explanatory:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import PathPatch

df = pd.DataFrame(np.random.rand(140, 4), columns=['A', 'B', 'C', 'D'])

df['models'] = pd.Series(np.repeat(['model1','model2', 'model3', 'model4',     'model5', 'model6', 'model7'], 20))

bp_dict = df.boxplot(
    by="models",layout=(4,1),figsize=(6,8),
    return_type='both',
    patch_artist = True,
)

colors = ['b', 'y', 'm', 'c', 'g', 'b', 'r', 'k', ]
for row_key, (ax,row) in bp_dict.iteritems():
    ax.set_xlabel('')
    for i,box in enumerate(row['boxes']):
        box.set_facecolor(colors[i])

plt.show()

结果图如下:

希望这会有所帮助.

这篇关于更改pandas boxplot子图中单个盒子的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆