Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bar chart in matplotlib shows less bars when having big range on x coordinates

What am I doing wrong here with a bar chart in python and matplotlib? The first plot is good, the second has a much wider range on the x-axis up to 1500. Notice in the second plot that most of the bars on the low scale disappear, but also the bar at 1500 is not shown.

I tried setting the width=0.8 in the bar() method, but that does not help.

With a logarithmic x-axis (using plt.xscale('log') ) it seems to work fine

import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(12, 6))

plt.bar(np.array([1,2,3,4,11,12]), np.array([10,2,1,1,3,10]))
plt.show()
#Then I close the figure and run this:
plt.bar(np.array([1,2,3,4,11,1500]), np.array([10,2,1,1,3,10]))
plt.show()

First plot, good Second plot, bad

like image 770
aless80 Avatar asked Dec 24 '22 12:12

aless80


1 Answers

Bars are by default 1 data units wide. The axes is ~600 pixels wide, but has ~1500 units. The chances you will see any single bar is hence 600/1500*1 = 40%. In that sense it's bad luck that you don't see the bar at x=1500. The other bars are so close together that you don't see which one of them is actually shown.

Instead of relying on the chances of seeing a bar, you would rather make the bar wide enough such that it can be seen safely. E.g. using a width of 5

plt.bar(np.array([1,2,3,4,11,1500]), np.array([10,2,1,1,3,10]), width=5)

Alternatively you could also show a stem plot, i.e. a plot with lines instead of bars,

plt.stem(np.array([1,2,3,4,11,1500]), np.array([10,2,1,1,3,10]),markerfmt=" ", basefmt=" ")
plt.ylim(0,None)
like image 200
ImportanceOfBeingErnest Avatar answered Dec 28 '22 06:12

ImportanceOfBeingErnest