将子图添加到程序会改变直方图的显示方式

Adding subplot to a program changes the way histograms are displayed

我正在使用取自 matplotlib 网站 this page 的 Pyplot 直方图示例代码作为构建其他内容的起点。

当我想修改它以使用子图(目的是使用其他子图来显示其他类型的图)时,如以下代码所示,输出全部搞砸了,直方图分布在多个图上,即使我只引用第一个元素。我错过了什么?

原代码:

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)

num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()

修改后的代码:

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

f, axarr = plt.subplots(3, sharex=False, sharey=False)
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
axarr[0].plot(bins, y, 'r--')
axarr[0].set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
plt.show()

您需要了解子图的工作原理。看一些例子 here

这是让 3 个子图做不同事情的代码。在这里,我再次绘制了同一个直方图 3 次,但是你可以随意更改它。

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(311) # This represents a (3x1) grid (row x col) and we are plotting the (1) subplot. The last number increments row-wise.

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50

# the histogram of the data
n, bins, patches = ax.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax.plot(bins, y, 'r--')
ax.set_title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

ax2 = fig.add_subplot(312) # Second subplot

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50

# the histogram of the data
n, bins, patches = ax2.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax2.plot(bins, y, 'r--')

ax3 = fig.add_subplot(313) # And the third subplot

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
num_bins = 50

# the histogram of the data
n, bins, patches = ax3.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
ax3.plot(bins, y, 'r--')
plt.show()