Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force the Y axis to only use integers in Matplotlib? [duplicate]

I'm plotting a histogram using the matplotlib.pyplot module and I am wondering how I can force the y-axis labels to only show integers (e.g. 0, 1, 2, 3 etc.) and not decimals (e.g. 0., 0.5, 1., 1.5, 2. etc.).

I'm looking at the guidance notes and suspect the answer lies somewhere around matplotlib.pyplot.ylim but so far I can only find stuff that sets the minimum and maximum y-axis values.

def doMakeChart(item, x):     if len(x)==1:         return     filename = "C:\Users\me\maxbyte3\charts\\"     bins=logspace(0.1, 10, 100)     plt.hist(x, bins=bins, facecolor='green', alpha=0.75)     plt.gca().set_xscale("log")     plt.xlabel('Size (Bytes)')     plt.ylabel('Count')     plt.suptitle(r'Normal Distribution for Set of Files')     plt.title('Reference PUID: %s' % item)     plt.grid(True)     plt.savefig(filename + item + '.png')     plt.clf() 
like image 984
Jay Gattuso Avatar asked Aug 21 '12 07:08

Jay Gattuso


People also ask

How do you restrict Y-axis in Python?

To plot the boxplot, use boxplot() function. To set the y-axis limit, we use axis() method and we set xmin and xmax to None and ymin and ymax to -0.75 and 1.5 respectively.

How do I restrict axis in Matplotlib?

Import matplotlib. To set x-axis scale to log, use xscale() function and pass log to it. To plot the graph, use plot() function. To set the limits of the x-axis, use xlim() function and pass max and min value to it. To set the limits of the y-axis, use ylim() function and pass top and bottom value to it.

How do I avoid scientific notation in Matplotlib?

If you want to disable both the offset and scientific notaion, you'd use ax. ticklabel_format(useOffset=False, style='plain') .


2 Answers

Here is another way:

from matplotlib.ticker import MaxNLocator  ax = plt.figure().gca() ax.yaxis.set_major_locator(MaxNLocator(integer=True)) 
like image 146
galath Avatar answered Sep 20 '22 15:09

galath


If you have the y-data

y = [0., 0.5, 1., 1.5, 2., 2.5] 

You can use the maximum and minimum values of this data to create a list of natural numbers in this range. For example,

import math print range(math.floor(min(y)), math.ceil(max(y))+1) 

yields

[0, 1, 2, 3] 

You can then set the y tick mark locations (and labels) using matplotlib.pyplot.yticks:

yint = range(min(y), math.ceil(max(y))+1)  matplotlib.pyplot.yticks(yint) 
like image 24
Chris Avatar answered Sep 19 '22 15:09

Chris