我有一组如下所示的数据,是否可以用自己的索引标记每个条形图?例如,对于第一组3个条形图,xticklabel应分别为红色,绿色,蓝色条的[data1a,data1b,data1c]。使用下面的代码,我只能使用' data1a'
进行标记d1label = ['data1a', 'data2a']
data1 = [204.24, 224.24]
d2label = ['data1b', 'data2b']
data2 = [206.24, 226.24]
d3label = ['data1c', 'data2c']
data3 = [208.24, 228.24]
def plot_tribar(logfile, ylabel, d1label, data1, d2label, data2, d3label, data3):
fig, ax = plt.subplots()
ind = np.arange(len(data1))
width = 0.3 # the width of the bars
rects1 = ax.bar(ind, data1, width, color='r', label='Bar1')
rects2 = ax.bar(ind+width, data2, width, color='g', label='Bar2')
rects3 = ax.bar(ind+(2*width), data3, width, color='b', label='Bar3')
handles, labels = ax.get_legend_handles_labels()
fontP = FontProperties()
fontP.set_size('small')
ax.legend(handles, labels, loc='best', prop=fontP)
ax.set_xticks(ind+width)
ax.set_xticklabels(d1label)
ax.set_ylabel(ylabel)
fig.autofmt_xdate()
def autolabel(rects):
for rect in rects:
height = rect.get_height()
if height >= 1:
ax.text(rect.get_x()+rect.get_width()/2., 1.01*height, '%d'%int(height), ha='center', va='bottom', fontsize=10)
autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
plt.show()
答案 0 :(得分:2)
这就是你想要的吗?
from matplotlib import pyplot as plt
import numpy as np
d1label = ['data1a', 'data2a']
data1 = [204.24, 224.24]
d2label = ['data1b', 'data2b']
data2 = [206.24, 226.24]
d3label = ['data1c', 'data2c']
data3 = [208.24, 228.24]
width = 0.3
data = np.concatenate([data1, data2, data3])
labels = np.concatenate([d1label, d2label, d3label])
colors = np.repeat(["r", "g", "b"], [len(data1), len(data2), len(data3)])
idx = np.arange(len(data1))
x = np.concatenate([idx, idx+width, idx+width*2])
plt.bar(x, data, width=0.3, color=colors)
ax = plt.gca()
ax.set_xticks(x + width*0.5)
ax.set_xticklabels(labels);
情节: