【问题标题】:matplotlib hist() autocropping rangematplotlib hist() 自动裁剪范围
【发布时间】:2014-07-16 05:56:39
【问题描述】:

我正在尝试在特定范围内制作直方图,但 matplotlib.pyplot.hist() 函数不断将范围裁剪到包含条目的 bin 中。一个玩具例子:

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()

给出一个范围为 [-100,100] 的图。为什么范围不是指定的 [-500,500]?

(我使用的是 Enthought Canopy 1.4,很抱歉,我没有足够高的代表来发布该情节的图像。)

【问题讨论】:

    标签: python matplotlib range histogram


    【解决方案1】:

    实际上,如果您使用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()
    

    如果您想在大于[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()
    

    【讨论】:

    • 好的,太好了。或者以更面向对象的方式,我可以使用 ax.hist(x, bins=nbins,range=[xmin,xmax]) ax.axis(xmin=xmin,xmax=xmax)
    • 是的。或ax.set_xlim(xmin=xmin, xmax=xmax).
    【解决方案2】:

    以下代码用于在两个子图上设置相同的 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)
    

    【讨论】:

      猜你喜欢
      • 2015-03-26
      • 2014-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2022-01-22
      • 2011-03-18
      相关资源
      最近更新 更多