19

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:

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?

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

Keith
  • 4,646
  • 7
  • 43
  • 72

2 Answers2

31

Actually, it works if you specify with range an interval shorter than [-100, 100]. For example, this work :

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 xlim propertie of the plot.

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()
Ger
  • 9,076
  • 10
  • 37
  • 48
0

the following code is for making the same y axis limit on two subplots

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)
Jingkai Xu
  • 31
  • 2