0

I wish to plot Pandas DataFrame with different columns on different vertical axes.

import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
    'a': [1, 2, 3, 4, 5],
    'b': [2, 3, 2, 3, 2],
    'c': [10, 20, 10, 10, 30]
    }
)

This works as intended.

fig, ax1 = plt.subplots(figsize=(15, 10))
ax2 = ax1.twinx()
df[['a', 'b']].plot(kind='bar', stacked=True, grid=True, ax=ax1)
df['c'].plot(kind='line', color='black', ax=ax2)
ax1.set_ylabel('left label')
ax2.set_ylabel('right label')
plt.show()

fig1

But what I add a DatetimeIndex, then the bar plot disappears. Why this doesn't work?

df.set_index(pd.date_range('2021-01-01','2021-01-05'), inplace=True)

fig2

Pinti
  • 113
  • 1
  • 4
  • 2
    Your bar plot is categorical, the lineplot numerical. Mayhem follows. You can tell the line plot with [`use_index=False`](https://stackoverflow.com/a/54481422/8881141) to be plotted like in the first example. If that is what you want (unevenly spaced dates will be presented evenly spaced) is not clear. – Mr. T Mar 05 '21 at 12:58
  • Aha! Now it makes sense, yes `use_index=False` fixes my problem. Thank you. – Pinti Mar 05 '21 at 13:09

0 Answers0