将多个直方图绘制为网格 [英] Plot multiple histograms as a grid

查看:77
本文介绍了将多个直方图绘制为网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用元组列表在同一窗口上绘制多个直方图.我设法使它一次只绘制一个元组,而我似乎无法使其与所有它们一起使用.

I am trying to plot multiple histograms on the same window using a list of tuples. I have managed to get it to sketch only 1 tuple at a time and I just can't seem to get it to work with all of them.

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等,但是我如何对其进行泛化以使其绘制所有元组.

As you can see from the above code, I can plot one tuple at a time say q1,q2 etc but how do I generalise it so that it plots all of them.

我试图模仿这个 python绘制多个直方图,这正是我所要做的想要但是我没有运气.

I've tried to mimic this python plot multiple histograms, which is exactly what I want however I had no luck.

谢谢您的时间:)

推荐答案

您需要使用 Axes.hist ,但是我一直喜欢使用 ax.bar ,根据np.unique的结果,该结果还可以返回唯一值的计数:

You need to define a grid of axes with plt.subplots taking into account the amount of tuples in the list, and how many you want per row. Then iterate over the returned axes, and plot the histograms in the corresponding axis. You could use Axes.hist, but I've always preferred to use ax.bar, from the result of np.unique, which also can return the counts of unique values:

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()

您可以针对喜欢的3行,将上面的内容自定义为任意数量的行/列:

You can customise the above to whatever amount of rows/cols you prefer, for 3 rows for instance:

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()

这篇关于将多个直方图绘制为网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆