将子图中的直方图条宽度设置为相等

时间:2014-12-04 05:15:06

标签: python matplotlib histogram

我正在将三个直方图绘制为Matplotlib中的子图,虽然我可以为每个直方图获得相同数量的条形图,但我仍然会生成不同的条形宽度。如何使每个子图的条宽度相等?我假设sharex = True会这样做,但显然不是这样......

谢谢!

f, axarr = plt.subplots(3, sharex=True, sharey=True)
f.suptitle("Nearest Neighbor", fontsize=14)

axarr[0].hist(actual_nn);
axarr[0].set_title('Actual')
axarr[1].hist(random_nn);
axarr[1].set_title('Random')![enter image description here][1]
axarr[2].hist(poisson_nn);
axarr[2].set_title('Poisson')

1 个答案:

答案 0 :(得分:1)

问题是每个bin根据数据在不同位置开始。 您可以通过在调用直方图时设置bin以参数范围开始的位置来解决此问题。 (不要混淆功能范围())

import matplotlib.pyplot as plt
import numpy as np

#set value for testing
actual_nn = np.random.randn(100)
random_nn = np.random.randn(100)
poisson_nn = np.random.randn(100)

f, axarr = plt.subplots(3, sharex=True, sharey=True)
f.suptitle("Nearest Neighbor", fontsize=14)

axarr[0].hist(actual_nn, range = (-3,3)); # range parameter set the start and the end of the bin
axarr[0].set_title('Actual')
axarr[1].hist(random_nn, range = (-3,3));
axarr[1].set_title('Random')
axarr[2].hist(poisson_nn, range = (-3,3));
axarr[2].set_title('Poisson')

您可以在此处获取有关范围参数的更多信息:http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist