Skip to content Skip to sidebar Skip to footer

Python Matplotlib Bars Overlapping Although Width < 1

I am trying to plot a number of bar charts with matplotlib having exactly 26 timestamps / slots at the x-axis and two integers for the y-axis. For most data sets this scales fine,

Solution 1:

The width of the bar is the width in data units. I.e. if you want to have a bar of width 1 minute, you would set the width to

plt.bar(..., width=1./(24*60.))

because the numeric axis unit for datetime axes in matplotlib is days and there are 24*60 minutes in a day.

For an automatic determination of the bar width, you may say that you want to have the bar width the smallest difference between any two successive values from the input time list. In that case, something like the following will do the trick

import numpy as np
import matplotlib.pyplot as plt
import datetime
import matplotlib.dates

t = [datetime.datetime(2017,9,12,8,i) for i inrange(60)]
x = np.random.rand(60)

td = np.diff(t).min()
s1 = matplotlib.dates.date2num(datetime.datetime.now())
s2 = matplotlib.dates.date2num(datetime.datetime.now()+td)

plt.bar(t, x, width=s2-s1, ec="k")

plt.show()

enter image description here

Post a Comment for "Python Matplotlib Bars Overlapping Although Width < 1"