gpt4 book ai didi

python - 如何使用 matplotlib 在单独的图形上创建多个直方图?

转载 作者:太空宇宙 更新时间:2023-11-03 12:24:09 28 4
gpt4 key购买 nike

我有 5 个数据集,我想从中创建 5 个单独的直方图。目前他们都在一张图表上。我该如何更改它以生成两个单独的图表?

为简单起见,在下面的示例中,我只显示了两个直方图。我正在查看角度 a 在 3 个不同时间的分布以及角度 b 的分布。

n, bins, patches = plt.hist(a)
plt.xlabel('Angle a (degrees)')
plt.ylabel('Frequency')
n, bins, patches = plt.hist(b)
label='2pm,3pm,4pm'
loc = 'center'
plt.legend(label, loc)

plt.xlabel('Angle b(degrees)')
plt.title('Histogram of b')
plt.ylabel('Frequency')
label='2pm,3pm,4pm'
loc = 'center'
plt.legend(label, loc)

plt.show()

最佳答案

这可能是你想使用 matplotlib 的 object-oriented interface 的时候.有几种方法可以处理这个问题。

首先,您可能希望每个绘图都在一个完全独立的图形上。在这种情况下,matplotlib 可让您跟踪各种数字。

import numpy as np
import matplotlib.pyplot as plt

a = np.random.normal(size=200)
b = np.random.normal(size=200)

fig1 = plt.figure()
ax1 = fig1.add_subplot(1, 1, 1)
n, bins, patches = ax1.hist(a)
ax1.set_xlabel('Angle a (degrees)')
ax1.set_ylabel('Frequency')

fig2 = plt.figure()
ax2 = fig2.add_subplot(1, 1, 1)
n, bins, patches = ax2.hist(b)
ax2.set_xlabel('Angle b (degrees)')
ax2.set_ylabel('Frequency')

或者,您可以将图形分成多个子图,并在每个子图中绘制直方图。在这种情况下,matplotlib 可以让您跟踪各种子图。

fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)

n, bins, patches = ax1.hist(a)
ax1.set_xlabel('Angle a (degrees)')
ax1.set_ylabel('Frequency')

n, bins, patches = ax2.hist(b)
ax2.set_xlabel('Angle b (degrees)')
ax2.set_ylabel('Frequency')

回答this question解释 add_subplot 中的数字。

关于python - 如何使用 matplotlib 在单独的图形上创建多个直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25430471/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com