我正试图使用一个元组列表在同一窗口中绘制多个直方图。我设法让它一次只绘制一个元组,但我似乎无法让它与所有元组一起工作。
import numpy as np
import matplotlib.pyplot as plt
a = [(1, 2, 0, 0, 0, 3, 3, 1, 2, 2), (0, 2, 3, 3, 0, 1, 1, 1, 2, 2), (1, 2, 0, 3, 0, 1, 2, 1, 2, 2),(2, 0, 0, 3, 3, 1, 2, 1, 2, 2),(3,1,2,3,0,0,1,2,3,1)] #my list of tuples
q1,q2,q3,q4,q5,q6,q7,q8,q9,q10 = zip(*a) #split into [(1,0,1,2,3) ,(2,2,2,0,1),..etc] where q1=(1,0,1,2,3)
labels, counts = np.unique(q1,return_counts=True) #labels = 0,1,2,3 and counts the occurence of 0,1,2,3
ticks = range(len(counts))
plt.bar(ticks,counts, align='center')
plt.xticks(ticks, labels)
plt.show()
从上面的代码中可以看出,我可以一次绘制一个元组,比如q1,q2等,但我如何使它能绘制所有的元组。
我试着模拟了一下 绘制多个直方图这正是我想要的,然而我没有运气。
谢谢你的时间:)
解决方案:
您需要用以下方法定义一个轴的网格 plt.subplots
考虑到列表中图元组的数量,以及每行想要多少个图元组。然后对返回的轴进行迭代,并在相应的轴上绘制直方图。您可以使用 Axes.hist但我一直喜欢用 ax.bar
,从结果来看 np.unique
,它也可以返回唯一值的计数。
from matplotlib import pyplot as plt
import numpy as np
l = list(zip(*a))
n_cols = 2
fig, axes = plt.subplots(nrows=int(np.ceil(len(l)/n_cols)),
ncols=n_cols,
figsize=(15,15))
for i, (t, ax) in enumerate(zip(l, axes.flatten())):
labels, counts = np.unique(t, return_counts=True)
ax.bar(labels, counts, align='center', color='blue', alpha=.3)
ax.title.set_text(f'Tuple {i}')
plt.tight_layout()
plt.show()
你可以自定义上面的内容,以达到你所喜欢的任何数量的rowscols,如 3
比如说,行。
l = list(zip(*a))
n_cols = 3
fig, axes = plt.subplots(nrows=int(np.ceil(len(l)/n_cols)),
ncols=n_cols,
figsize=(15,15))
for i, (t, ax) in enumerate(zip(l, axes.flatten())):
labels, counts = np.unique(t, return_counts=True)
ax.bar(labels, counts, align='center', color='blue', alpha=.3)
ax.title.set_text(f'Tuple {i}')
plt.tight_layout()
plt.show()