首页 > 解决方案 > 箱线图组如何在 matplotlib 中具有不同的颜色和相应的图例?

问题描述

此代码为细分为三组数据的样本生成单独的箱线图。因此,数据集 1 有样本 A、B 和 C 等。我希望每个分组中的框具有不同的颜色,而组中的每个图都是相同的颜色。此外,如何制作具有相应颜色的图例?

import matplotlib.pyplot as plt
import numpy as np
import random

#build dataset as dictionary
data = {}
data['dataset1'] = {}
data['dataset2'] = {}
data['dataset3'] = {}

#simulate data
n = 100
for k,v in data.iteritems():
    upper = random.randint(0, 1000)
    v['sample A'] = np.random.uniform(0, upper, size=n)
    v['sample B'] = np.random.uniform(0, upper, size=n)
    v['sample C'] = np.random.uniform(0, upper, size=n)

fig, axes = plt.subplots(ncols=3, sharey=True)
fig.subplots_adjust(wspace=0)

#build subplots
for ax, name in zip(axes, ['dataset1', 'dataset2', 'dataset3']):
    ax.boxplot([data[name][item] for item in ['sample A', 'sample B', 'sample C']])
    ax.set(xticklabels=['sample A', 'sample B', 'sample C'])
    ax.margins(0.05)

#plot labels
for ax in fig.axes:
    plt.sca(ax)
    plt.xticks(ha = 'right', rotation=45)

plt.show()

标签: pythonmatplotlibboxplot

解决方案


import matplotlib.pyplot as plt
import numpy as np
import random

#build dataset as dictionary
data = {}
data['dataset1'] = {}
data['dataset2'] = {}
data['dataset3'] = {}

#simulate data
n = 100
for k,v in data.items():
    upper = random.randint(0, 1000)
    v['sample A'] = np.random.uniform(0, upper, size=n)
    v['sample B'] = np.random.uniform(0, upper, size=n)
    v['sample C'] = np.random.uniform(0, upper, size=n)

fig, axes = plt.subplots(ncols=3, sharey=True)
fig.subplots_adjust(wspace=0)

#build subplots
colors = ['pink', 'lightblue', 'lightgreen']
for ax, name in zip(axes, ['dataset1', 'dataset2', 'dataset3']):
    bplot = ax.boxplot([data[name][item] for item in ['sample A', 'sample B', 'sample C']], patch_artist=True)
    for patch, color in zip(bplot['boxes'], colors):
        patch.set_facecolor(color)
    ax.set(xticklabels=['sample A', 'sample B', 'sample C'])
    ax.margins(0.05)

#plot labels
for ax in fig.axes:
    plt.sca(ax)
    plt.xticks(ha = 'right', rotation=45)

# place legend
plt.legend([bplot["boxes"][0], bplot["boxes"][1], bplot["boxes"][2]],
           ['A', 'B', 'C'],
           bbox_to_anchor=(1, 1))

plt.show()

推荐阅读