23

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?

cottontail
  • 10,268
  • 18
  • 50
  • 51
user1473483
  • 305
  • 1
  • 3
  • 7

2 Answers2

30

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.

Community
  • 1
  • 1
cosmosis
  • 6,047
  • 3
  • 32
  • 28
-1

A very simple way to "magnify" the top ends of the bars is to log-scale the y-axis.

plt.bar(x, y, log=True)

result1

The yticklabels get a scientific notation as a result but it's relatively simple to return to plain formatting by formatting both major and minor ticks.

import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter

x = [1,2,3,4,5]
y = [1000, 1002, 1001, 1003, 1005]

# log scale
plt.bar(x, y, log=True)
# remove scientific notation
plt.gca().yaxis.set(major_formatter=ScalarFormatter(), minor_formatter=ScalarFormatter());

result2

cottontail
  • 10,268
  • 18
  • 50
  • 51