3

I'm trying to plot a double bar plot in matplotlib, where the x-axis is a date value. My dataframe is the following:

+------------+----------+----------+
|            | Column A | Column B |
+------------+----------+----------+
| 2020-03-28 |        4 |      0.0 |
+------------+----------+----------+
| 2020-03-29 |      250 |     58.0 |
+------------+----------+----------+
| 2020-03-30 |       72 |     10.0 |
+------------+----------+----------+
| 2020-03-31 |       10 |      0.0 |
+------------+----------+----------+
| 2020-04-01 |        7 |      0.0 |
+------------+----------+----------+
|        ... |      ... |      ... |
+------------+----------+----------+
| 2020-05-12 |        6 |      0.0 |
+------------+----------+----------+
| 2020-05-13 |        2 |      0.0 |
+------------+----------+----------+
| 2020-05-14 |        9 |      0.0 |
+------------+----------+----------+
| 2020-05-15 |        5 |      0.0 |
+------------+----------+----------+
| 2020-05-16 |       35 |      1.0 |
+------------+----------+----------+

I wish to plot it with a bar plot, with the following code:

g.plot.bar()
ax = plt.gca()
ax.set_yscale('log')
ax.xaxis_date() 
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d'))

The last line is to set a formatter to the ticks in the x-axis, since if not, it will show all days within the entire month. When I try this, it raises the following exception:

ValueError: DateFormatter found a value of x=0, which is an illegal date; this usually occurs because you have not informed the axis that it is plotting dates, e.g., with ax.xaxis_date()

I've searched a lot of this error, but I can't figure what it's goinng wrong with the code/data...

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
olenscki
  • 487
  • 7
  • 22

1 Answers1

2

Allegedly pandas doesn't handle custom date formats all too well.
So we can use base matplotlib instead.
This other SO answer helped me: https://stackoverflow.com/a/59739281/42346

import matplotlib.pyplot as plt, numpy as np, matplotlib.dates as mdates 

x = mdates.datestr2num(g.index.strftime('%m-%d')) 
w = 0.25
fig = plt.figure(figsize=(8, 4)) 
ax = fig.add_subplot(111) 
ax.bar(x - w, g['Column A'], width=2 * w, align='center') 
ax.bar(x + w, g['Column B'], width=2 * w, align='center') 
ax.xaxis_date() 
ax.xaxis.set_major_locator(mdates.AutoDateLocator()) 
ax.xaxis.set_major_formatter(mdates.DateFormatter("%m-%d"))
plt.show()

Result:

enter image description here

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223