JAL*_*ism 7 python matplotlib boxplot dataframe pandas
这是参考以下问题,其中讨论了调整子图标题和布局的选项: 修改熊猫箱线图输出
我的要求是更改每个子图中各个框的颜色(如下所示):
以下是共享链接中用于调整子图的标题和轴属性的代码:
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()
Run Code Online (Sandbox Code Playgroud)
我尝试使用: ax.set_facecolor('color') 属性,但没有成功获得所需的结果。
我也尝试访问 bp['boxes'] 但显然它不可用。我需要对 bp 中存储的数据结构有一些了解,以便访问子图中的各个框。
期待
PS:我知道seaborn。但目前需要使用 df.boxplot 来理解和实现。谢谢
要调整 中框的颜色pandas.boxplot,您必须稍微调整代码。首先,您必须告诉boxplot实际用颜色填充框。您可以通过指定做到这一点patch_artist = True,因为是记录在这里。但是,您似乎无法指定颜色(默认为蓝色)——如果我错了,请任何人纠正我。这意味着您必须在之后更改颜色。幸运的是,pandas.boxplot提供了一个简单的选项,通过指定return_type = 'both' 查看这里的解释来获取箱线图中的艺术家作为返回值。pandas.Series根据您的DataFrame列和值,您得到的是带有键的键,这些键是包含Axes绘制箱线图的实例以及字典中箱线图的实际元素。我认为代码是不言自明的:
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()
Run Code Online (Sandbox Code Playgroud)
结果图如下所示:
希望这可以帮助。
尽管您将返回命名为df.boxplot bp,但它实际上是一个(n)()轴数组。检查轴以获取箱线图的各个部分很麻烦(但可能)。
首先,为了能够对盒子的内部进行着色,您需要将盒子变成补丁df.boxplot(..., patch_artist=True)。
然后,您需要在轴中的所有艺术家中找到框。
# We want to make the 4th box in the second axes red
axes[1].findobj(matplotlib.patches.Patch)[3].set_facecolor("red")
Run Code Online (Sandbox Code Playgroud)
完整代码:
import pandas as pd
import numpy as np
import matplotlib
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))
axes = df.boxplot(by="models", layout=(len(df.columns)-1,1), figsize=(6,8), patch_artist=True)
for ax in axes:
ax.set_xlabel('')
# We want to make the 4th box in the second axes red
axes[1].findobj(matplotlib.patches.Patch)[3].set_facecolor("red")
fig = axes[0].get_figure()
fig.suptitle('New title here')
plt.show()
Run Code Online (Sandbox Code Playgroud)