我使用matplotlib的箱形图并尝试使用标签为箱面分配颜色;使用类似于以下内容的代码:
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':'red', '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, widths = 0.25)
for b in boxplot_dict['boxes']:
lab = b.get_label()
print("Label property of box ", i, " is ", lab)
b.set_facecolor(color_dict[lab]) # <- This is what I would like to be able to do
ax.set_ylim([0,16])
plt.show()
我理解使用labels
作为输入参数来命名不同的箱图。但是,我注意到使用get_label
方法访问时框的label属性未设置为任何内容。
那么label属性(不是输入参数)有什么用?
答案 0 :(得分:3)
labels
中的ax.boxplot()
参数设置轴的xticklabels
,而不是框对象的标签(将在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
完整的代码是:
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,
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_facecolor(color_dict[lab])
i += 1
ax.set_ylim([0,16])
plt.show()
替代示例,设置框对象的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()