Description
Bug summary
I have a Pandas Series with monthly dates. The values are real gdp percentages. When trying to plot a bar chart, the chart is completely incorrect only showing small lines in incorrect locations.
Code for reproduction
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig, ax = plt.subplots()
data = pd.Series([ 5.2, np.nan, np.nan, 6.2, np.nan, np.nan, 3.3, np.nan, np.nan,
7. , np.nan, np.nan, -2. , np.nan, np.nan, -0.6, np.nan, np.nan,
2.7, np.nan, np.nan, 2.6, np.nan, np.nan, 2.2, np.nan, np.nan,
2.1, np.nan, np.nan, 4.9, np.nan, np.nan, 3.4, np.nan, np.nan,
1.3, np.nan, np.nan, np.nan, np.nan])
dates = pd.date_range(start='2021-01', periods=len(data), freq='M')
data.index = pd.to_datetime(dates, format='%Y-%m')
data = data.dropna() # removing this line has no effect, the behavior is consistent
ax.bar(data.index, data.values) # add `width=20` param to get correct output
plt.show()
Actual outcome
Expected outcome
Additional information
Initially I believed this had to do with the NaN values in the data. (My charting purposes are monthly not quarterly). Even removing NaN values with ffill()
or dropna()
did not produce better results.
Further debugging led me to consider if this was an issue with the dates and how they were formatted. I tried many different ways including manually setting the dates with matplotlib.ma.date2num
then plot.gca().xaxis.set_major_formatter()
but this didn't help either.
Switching to a standard plot()
instead of bar()
was even more inconsistent but worked if I set the NaN values to 0.
Eventually, I found manually setting the width=20
parameter caused the bar chart to behave correctly.
Operating system
Google Colaboratory
Matplotlib Version
3.7.1
Matplotlib Backend
module://matplotlib_inline.backend_inline
Python version
3.10.12
Jupyter version
No response
Installation
None