0

I have been trying to properly display a simple histogram with dates as x-axis and integers as y-axis. The example below happens to be a subplot (2 y-axis, 1 shared x-axis) but the problem is not there, it's rather the hist itself.

import datetime
import matplotlib
matplotlib.use('agg')   # server no need to display graphics
import matplotlib.pyplot as plt

# x-axis is 3 consecutive dates (days)
now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

# y1-axis is 3 numbers
y1 = [10, 0, 3]
y2 = [8, 0, 3]

fig, axarr = plt.subplots(2, sharex=True)
bins = range(1, len(x) + 1)
axarr[1].hist(y1, bins=len(x), edgecolor="k")
axarr[1].set_xticks(bins)
axarr[1].set_xticklabels(x)
axarr[1].set_yticks(range(0, max(y1) + 1))

# axarr[0] ommitted for simplicity

plt.savefig('a.png', bbox_inches='tight')

However the image I get is ...

enter image description here

stelios
  • 2,679
  • 5
  • 31
  • 41
  • Have you checked here: https://stackoverflow.com/questions/27083051/matplotlib-xticks-not-lining-up-with-histogram ? – Georgy Jul 13 '18 at 09:17
  • @Georgy Thank you, but finally it was a blunder of mine, I needed a `bar` graph instead. – stelios Jul 13 '18 at 09:27

2 Answers2

1

If you want dates on the x axis of your histogram, it is the dates that need to be the argument to hist.

now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

axarr[1].hist(x, edgecolor="k")

enter image description here

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Thanks. That's correct, you don't define y-values to histograms... That's why I need a `bar` graph apparently :S – stelios Jul 13 '18 at 09:28
  • +1. This answer addresses the title (Google led me here). See also https://stackoverflow.com/questions/29672375/histogram-in-matplotlib-time-on-x-axis – Rainald62 Feb 27 '22 at 14:52
0

You probably want a bar graph.

import datetime
import matplotlib
matplotlib.use('agg')   # server no need to display graphics
import matplotlib.pyplot as plt

# x-axis is 3 consecutive dates (days)
now = datetime.datetime.now().date()
x = [now, now + datetime.timedelta(days=1), now + datetime.timedelta(days=2)]

# y1-axis is 3 numbers
y1 = [10, 0, 3]
y2 = [8, 0, 3]

fig, axarr = plt.subplots(2, sharex=True)
axarr[1].bar(x, y1, edgecolor="k")
axarr[1].set_xticks(x)
axarr[1].set_xticklabels(x)

plt.savefig('a.png', bbox_inches='tight')

enter image description here

Rainald62
  • 706
  • 12
  • 19
pask
  • 899
  • 9
  • 19