我能够构建我需要的直方图。但是,这些条彼此重叠。
正如您所看到的,我更改了bars to 0.2
的宽度,但它仍然重叠。我在做什么错误?
from matplotlib import pyplot as plt
import numpy as np
from matplotlib.font_manager import FontProperties
from random import randrange
color = ['r', 'b', 'g','c','m','y','k','darkgreen', 'darkkhaki', 'darkmagenta', 'darkolivegreen', 'darkorange', 'darkorchid', 'darkred']
label = ['2','6','10','14','18','22','26','30','34','38','42','46']
file_names = ['a','b','c']
diff = [[randrange(10) for a in range(0, len(label))] for a in range(0, len(file_names))]
print diff
x = diff
name = file_names
y = zip(*x)
pos = np.arange(len(x))
width = 1. / (1 + len(x))
fig, ax = plt.subplots()
for idx, (serie, color,label) in enumerate(zip(y, color,label)):
ax.bar(pos + idx * width, serie, width, color=color, label=label)
ax.set_xticks(pos + width)
plt.xlabel('foo')
plt.ylabel('bar')
ax.set_xticklabels(name)
ax.legend()
plt.savefig("final" + '.eps', bbox_inches='tight', pad_inches=0.5,dpi=100,format="eps")
plt.clf()
以下是图表:
答案 0 :(得分:1)
正如您在下面的示例中所看到的,您可以使用大量简化版本的绘图代码轻松获得非重叠条形图。我建议你仔细看看x
和y
是否真的符合你的期望。 (并且当您在代码中查找错误时,尝试尽可能地简化代码。)
还要看一下条形width
的计算。您似乎使用了此数量的主题,而应该是每个主题的数量。
看一下这个例子:
import numpy as np
import matplotlib.pyplot as plt
subjects = ('Tom', 'Dick', 'Harry', 'Sally', 'Sue')
# number of bars per subject
n = 5
# y-data per subject
y = np.random.rand(n, len(subjects))
# x-positions for the bars
x = np.arange(len(subjects))
# plot bars
width = 1./(1+n) # <-- n.b., use number of bars, not number of subjects
for i, yi in enumerate(y):
plt.bar(x+i*width, yi, width)
# add labels
plt.xticks(x+n/2.*width, subjects)
plt.show()
这是结果图片:
供参考:
答案 1 :(得分:0)
问题在于,条形图的宽度是根据三个主题计算的,而不是每个主题的十二个条形图。这意味着你在每个x位置放置多个条形。尝试在适当的位置交换这些行来修复:
n = len(x[0]) # New variable with the right length to calculate bar width
width = 1. / (1 + n)
ax.set_xticks(pos + n/2. * width)