我正在使用来自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()
答案 0 :(得分:1)
您需要了解子图的工作原理。看一些例子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()