changing default x range in histogram matplotlib
Asked Answered
W

3

61

I would like to change the default x range for the histogram plot. The range of the data is from 7 to 12. However, by default the histogram starts right at 7 and ends at 13. I want it to start at 6.5 and end at 12.5. However, the ticks should go from 7 to 12.How do I do it?

import asciitable 
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import pylab
from pylab import xticks

data = asciitable.read(file)
hmag = data['col8']
visits = data['col14']
origin = data['col13']


n, bins, patches = plt.hist(hmag, 30, facecolor='gray', align='mid')
xticks(range(7,13))
pylab.rc("axes", linewidth=8.0)
pylab.rc("lines", markeredgewidth=2.0) 
plt.xlabel('H mag', fontsize=14)
plt.ylabel('# of targets', fontsize=14)
pylab.xticks(fontsize=15)
pylab.yticks(fontsize=15)
plt.grid(True)
plt.savefig('hmag_histogram.eps', facecolor='w', edgecolor='w', format='eps')
plt.show()
Westbrook answered 25/8, 2012 at 21:42 Comment(0)
P
98
plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')
Pea answered 25/8, 2012 at 23:35 Comment(5)
Thanks for your reply. However, doing so I get the following error: >> n, bins, patches = plt.hist(hmag, range=[6.5, 12.5], 30, facecolor='gray', align='mid') >>SyntaxError: non-keyword arg after keyword argWestbrook
You have to use the same order as I used above. Putting 30 after the range keyword will lead to a Syntaxerror.Pea
@aging_gorrila, the yrange is just a property of the plot and doesn't require recomputing the histogram. After you do the plot, you can just call ylim(a, b).Pea
Is there a way to set this automatically? Say, the range goes from xmin*-1.1 to xmax*1.1?Dreda
@Dreda you can set range=[-xmin * 1.1, xmax * 1.1] if you want. Just make sure that xmin and xmax are something that makes sense.Pea
C
12
import matplotlib.pyplot as plt


...


plt.xlim(xmin=6.5, xmax = 12.5)
Convergent answered 29/8, 2017 at 16:44 Comment(2)
This does not keep the number of bins defined in the bins parameter.Cuspidate
This works in python3 (assuming your xmin/xmax are large enough) can you give an example where it does not keep the bins count?Convergent
H
3

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 = [lower_limit,upper_limit]
ax[0].set_ylim(ylim)
ax[1].hist(data,normed =1, bins = num_bin, color = 'yellow' ,alpha = 1) 
ax[1].set_ylim(ylim)

just a reminder, plt.hist(range=[low, high]) the histogram auto crops the range if the specified range is larger than the max&min of the data points. So if you want to specify the y-axis range number, i prefer to use set_ylim

Hierarchize answered 11/7, 2019 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.