2

Previously I managed to create the following plot

enter image description here

import pandas as pd
import matplotlib.pyplot as plt

df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]})
df_prog.index = pd.date_range(start='2020-01-01 00', end='2020-01-01 02', freq='H')
df_prog.index = df_prog.index + pd.Timedelta(minutes=30)

Now I'm trying to once again create this plot but without success. My memory is failing me

I've tried

ax = df_prog.plot(kind='bar')
df_prog.plot(kind='line')

as described in Plot Pandas DataFrame as Bar and Line on the same one chart

But depending on which is chosen first, bar or line, only one is showed, and not both in the same figure.

Olba12
  • 305
  • 2
  • 14

2 Answers2

2

You need to convert the time axis to string. Then you can plot them together.

import pandas as pd
import matplotlib.pyplot as plt

df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]})
df_prog.index = pd.date_range(start='2020-01-01 00', end='2020-01-01 02', freq='H')
df_prog.index = df_prog.index + pd.Timedelta(minutes=30)

_, ax = plt.subplots()
df_prog.index = df_prog.index.astype(str)
df_prog.plot(kind='line', linestyle='-', marker='o', color='r', ax=ax)
df_prog.plot(kind='bar', ax=ax)

plt.show()

enter image description here

Spinor8
  • 1,587
  • 4
  • 21
  • 48
0

You are missing the ax=ax and use_index=Falsearguments in the line plot function. This will draw the line in the same plot as the bars and it will prevent the line plot from using the timestamps for the x-axis. Instead, the x-axis units will start at zero like for the bar plot, so that the line is aligned with the bars. No need to convert the index and no need for matplotlib.

import pandas as pd # v 1.1.3

# Create sample dataset
idx = pd.date_range(start='2020-01-01 00:30', periods=3, freq='60T')
df_prog = pd.DataFrame({"Prognos tim": [2, 3, 3]}, index=idx)

# Combine pandas line and bar plots
ax = df_prog.plot.bar(figsize=(8,5))
df_prog.plot(use_index=False, linestyle='-', marker='o', color='r', ax=ax)

# Format labels
ax.set_xticklabels([ts.strftime('%H:%M') for ts in df_prog.index])
ax.figure.autofmt_xdate(rotation=0, ha='center')

pd_line_bar_plot


If you omit the use_index=False argument, both the bars and line are still drawn in the same figure except that the x limits are constrained to the second plot you create. As you can see here for example:

ax = df_prog.plot.bar(figsize=(8,5))
df_prog.plot(linestyle='-', marker='o', color='r', ax=ax) # plot line in bars plot
ax.set_xlim(-0.5,2.5); # the bars are here
# ax.set_xlim(26297300, 26297450); # the line is here, the values are pandas period units

pd_line_bar_xlim

Patrick FitzGerald
  • 3,280
  • 2
  • 18
  • 30