Python matplotlib hist() 自动裁剪范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23887410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
matplotlib hist() autocropping range
提问by Keith
I am trying to make a histgram over a specific range but the matplotlib.pyplot.hist() function keeps cropping the range to the bins with entries in them. A toy example:
我正在尝试在特定范围内制作直方图,但 matplotlib.pyplot.hist() 函数不断将范围裁剪到带有条目的垃圾箱。一个玩具示例:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.uniform(-100,100,1000)
nbins = 100
xmin = -500
xmax = 500
fig = plt.figure();
ax = fig.add_subplot(1, 1, 1)
ax.hist(x, bins=nbins,range=[xmin,xmax])
plt.show()
Gives a plot with a range [-100,100]. Why is the range not [-500,500] as specified?
给出范围为 [-100,100] 的图。为什么范围不是指定的 [-500,500]?
(I am using the Enthought Canopy 1.4 and sorry but I do not have a high enough rep to post an image of the plot.)
(我正在使用 Enthought Canopy 1.4,抱歉,我没有足够高的代表来发布该图的图像。)
采纳答案by Ger
Actually, it works if you specify with rangean interval shorter than [-100, 100]. For example, this work :
实际上,如果您指定range的间隔小于[-100, 100]. 例如,这项工作:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.uniform(-100, 100, 1000)
plt.hist(x, bins=30, range=(-50, 50))
plt.show()
If you want to plot the histogram on a range larger than [x.min(), x.max()]you can change xlimpropertie of the plot.
如果您想在大于[x.min(), x.max()]您可以更改xlim绘图属性的范围内绘制直方图。
import numpy as np
import matplotlib.pyplot as plt
x = np.random.uniform(-100, 100, 1000)
plt.hist(x, bins=30)
plt.xlim(-500, 500)
plt.show()
回答by Jingkai Xu
the following code is for making the same y axis limit on two subplots
以下代码用于对两个子图进行相同的 y 轴限制
f ,ax = plt.subplots(1,2,figsize = (30, 13),gridspec_kw={'width_ratios': [5, 1]})
df.plot(ax = ax[0], linewidth = 2.5)
ylim = [df['min_return'].min()*1.1,df['max_return'].max()*1.1]
ax[0].set_ylim(ylim)
ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1)
ax[1].set_ylim(ylim)

