本文介绍了用于条形图的 matplotlib 多个 xticklabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一组如下所示的数据,是否可以用自己的索引标记每个条形图?例如,对于第一组 3 个条形图,红色、绿色、蓝色条形的 xticklabel 应分别为 [data1a, data1b, data1c].使用下面的代码,我只能用'data1a'标记
I've a set of data as shown below, is it possible to label each bar graph with their own index? For eg, for the first group of 3 bar graphs, the xticklabel should be [data1a, data1b, data1c] for Red,Green,Blue bar respectively. With the code below, I can only label with '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()
推荐答案
这是您想要的吗?
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);
剧情:
这篇关于用于条形图的 matplotlib 多个 xticklabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!