Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically setting y-axis limits for bar graph using matplotlib

Tags:

Here's an example of graphing large values.

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1000, 1002, 1001, 1003, 1005]
plt.bar(x,y) 
plt.show()

The y-axis starts at 0, so the bars all look equal. I know you can use plt.ylim to manually set the limits, but is there a way for matplotlib to automatically (and smartly) set the limits to reasonable values (like 998-1008), and also perhaps show an axis break?

like image 979
user1473483 Avatar asked Jun 26 '12 21:06

user1473483


People also ask

How do you set limits on the y axis?

Set y-Axis Limits for Specific AxesCall the tiledlayout function to create a 2-by-1 tiled chart layout. Call the nexttile function to create the axes objects ax1 and ax2 . Plot data into each axes. Then set the y-axis limits for the bottom plot by specifying ax2 as the first input argument to ylim .

How do I change the y axis values in MatPlotLib?

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.

How do you set the Y axis range in Python?

To set range of x-axis and y-axis, use xlim() and ylim() function respectively. To add a title to the plot, use the title() function. To add label at axes, use xlabel() and ylabel() functions. To visualize the plot, use the show() function.

What are the methods to adjust axis limits MatPlotLib?

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


1 Answers

A little bit of simple algebra will help fix the limits:

import matplotlib.pyplot as plt
import math
x = [1,2,3,4,5]
y = [1000, 1002, 1001, 1003, 1005]
low = min(y)
high = max(y)
plt.ylim([math.ceil(low-0.5*(high-low)), math.ceil(high+0.5*(high-low))])
plt.bar(x,y) 
plt.show()

In this way, you are able to find the difference between your y-values and use them to set the scale along the y-axis. I used math.ceil (as opposed to math.floor) in order to obtain the values you specified and ensure integers.

As far as an axis break goes, I'd suggest looking at this example.

like image 76
cosmosis Avatar answered Sep 18 '22 11:09

cosmosis