47

I know about plot_date() but is there a bar_date() out there?

The general method would be to use set_xticks and set_xticklabels, but I'd like something that can handle time scales from a few hours out to a few years (this means involving the major and minor ticks to make things readable).

I am plotting values associated with a specific time interval (that the bar spans). Here is the basic solution I used:

import matplotlib.pyplot as plt
import datetime
t = [datetime.datetime(2010, 12, 2, 22, 0), datetime.datetime(2010, 12, 2, 23, 0),
     datetime.datetime(2010, 12, 10, 0, 0), datetime.datetime(2010, 12, 10, 6, 0)]
y = [4, 6, 9, 3]
interval = 1.0 / 24.0  #1hr intervals, but maplotlib dates have base of 1 day
ax = plt.subplot(111)
ax.bar(t, y, width=interval)
ax.xaxis_date()
plt.show()
cottontail
  • 10,268
  • 18
  • 50
  • 51
Adam Greenhall
  • 4,818
  • 6
  • 30
  • 31

2 Answers2

61

All plot_date does is plot the function and the call ax.xaxis_date().

All you should need to do is this:

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

x = [datetime.datetime(2010, 12, 1, 10, 0),
    datetime.datetime(2011, 1, 4, 9, 0),
    datetime.datetime(2011, 5, 5, 9, 0)]
y = [4, 9, 2]

ax = plt.subplot(111)
ax.bar(x, y, width=10)
ax.xaxis_date()

plt.show()

bar graph with x dates

Tim
  • 1,466
  • 16
  • 24
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • Thanks! Specifically I am plotting values associated with a specific time interval (that the bar spans). I think I have it figured out now - I'll edit above. – Adam Greenhall May 05 '11 at 22:37
0

In newer versions of matplotlib (e.g. 3.7.1), plt.plot() and plt.bar() can directly handle datetime input, there's no need to use date2num etc. So if the x-axis is datetime, a timedelta can be passed directly as bar width.

import matplotlib.pyplot as plt
import datetime

t = [datetime.datetime(2010, 12, 2, 22, 0), datetime.datetime(2010, 12, 2, 23, 0),
     datetime.datetime(2010, 12, 10, 0, 0), datetime.datetime(2010, 12, 10, 6, 0)]
y = [4, 6, 9, 3]

interval = datetime.timedelta(hours=1)     # <----- timedelta of 1 hour

fig, ax = plt.subplots()
ax.bar(t, y, width=interval)
fig.autofmt_xdate()

result


In the OP and in the answer by @Joe Kington, xaxis_date() is used. It's not necessary if the data passed to x-axis is already datetime (as in the code above). But it's necessary if the data passed as x-data is numeric but you want to treat it as datetime.

t = [14946.25, 14946.29, 14953.33, 14953.58] # <---- numbers instead of datetime
y = [4, 6, 9, 3]
interval = 1 / 24                            # <---- has to be numeric because `t` is numeric

fig, ax = plt.subplots()
ax.bar(t, y, width=interval)
ax.xaxis_date()                              # <---- treat x-ticks as datetime
fig.autofmt_xdate()
cottontail
  • 10,268
  • 18
  • 50
  • 51