赞
踩
ax.boxplot()中的labels参数设置轴的xticklabels,而不是box对象的标签(这将在ax.legend()中使用)。在
因此,您可以从ax.get_xticklabels访问所需的标签。要在代码中替换的相关代码段是:for b in boxplot_dict['boxes']:
lab = ax.get_xticklabels()[i].get_text()
print("Label property of box {0} is {1}".format(i, lab))
b.set_facecolor(color_dict[lab])
i += 1
完整的代码应该是:
^{pr2}$
另一个例子,设置box对象的label属性from matplotlib import pyplot as plt
import numpy as np
data = {}
data['a'] = np.arange(12)+1
data['b'] = np.arange(14)+1
data['c'] = np.arange(8)+1
color_dict = {'trt_a':'orange', 'trt_b':'blue', 'trt_c':'green'}
controls = ['trt_a', 'trt_b', 'trt_c']
fig, ax = plt.subplots()
boxplot_dict = ax.boxplot(
[data[x] for x in ['a', 'b', 'c']],
positions = [1, 1.5, 2],
labels = controls,
# patch_artist = True, # Legend isn't working with patch objects..
widths = 0.25)
i=0
for b in boxplot_dict['boxes']:
lab = ax.get_xticklabels()[i].get_text()
print("Label property of box {0} is {1}".format(i, lab))
b.set_color(color_dict[lab])
b.set_label(lab)
i += 1
ax.set_ylim([0,16])
ax.legend()
plt.show()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。