Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change y range to start from 0 with matplotlib

I am using matplotlib to plot data. Here's a code that does something similar:

import matplotlib.pyplot as plt f, ax = plt.subplots(1) xdata = [1, 4, 8] ydata = [10, 20, 30] ax.plot(xdata, ydata) plt.show(f) 

This shows a line in a graph with the y axis that goes from 10 to 30. While I am satisfied with the x range, I would like to change the y range to start from 0 and adjust on the ymax to show everything.

My current solution is to do:

ax.set_ylim(0, max(ydata)) 

However I am wondering if there is a way to just say: autoscale but starts from 0.

like image 556
Maxime Chéramy Avatar asked Mar 25 '14 17:03

Maxime Chéramy


People also ask

How do I make Y axis start at 0 in matplotlib?

To show (0,0) on matplotlib graph at the bottom left corner, we can use xlim() and ylim() methods.

How do I change the Y axis range in matplotlib?

To change the range of X and Y axes, we can use xlim() and ylim() methods.

How do you change the range of a matplotlib plot?

In matplotlib, to set or get X-axis and Y-axis limits, use xlim() and ylim() methods, accordingly.

How do I change the y axis values in Python?

To specify the value of axes, create a list of characters. Use xticks and yticks method to specify the ticks on the axes with x and y ticks data points respectively. Plot the line using x and y, color=red, using plot() method. Make x and y margin 0.


2 Answers

The range must be set after the plot.

import matplotlib.pyplot as plt f, ax = plt.subplots(1) xdata = [1, 4, 8] ydata = [10, 20, 30] ax.plot(xdata, ydata) ax.set_ylim(ymin=0) plt.show(f) 

If ymin is changed before plotting, this will result in a range of [0, 1].

Edit: the ymin argument has been replaced by bottom:

ax.set_ylim(bottom=0) 
like image 189
Maxime Chéramy Avatar answered Oct 05 '22 06:10

Maxime Chéramy


Try this

import matplotlib.pyplot as plt xdata = [1, 4, 8] ydata = [10, 20, 30] plt.plot(xdata, ydata) plt.ylim(ymin=0)  # this line plt.show() 

doc string as following:

>>> help(plt.ylim) Help on function ylim in module matplotlib.pyplot:  ylim(*args, **kwargs)     Get or set the *y*-limits of the current axes.      ::        ymin, ymax = ylim()   # return the current ylim       ylim( (ymin, ymax) )  # set the ylim to ymin, ymax       ylim( ymin, ymax )    # set the ylim to ymin, ymax      If you do not specify args, you can pass the *ymin* and *ymax* as     kwargs, e.g.::        ylim(ymax=3) # adjust the max leaving min unchanged       ylim(ymin=1) # adjust the min leaving max unchanged      Setting limits turns autoscaling off for the y-axis.      The new axis limits are returned as a length 2 tuple. 
like image 44
WeizhongTu Avatar answered Oct 05 '22 07:10

WeizhongTu