Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Pandas DataFrame - Cannot plot bars and lines on the same axes

I might be doing something wrong but I'm struggling to achieve the below:

# plot bars and lines in the same figure, sharing both x and y axes.
df = some DataFrame with multiple columns
_, ax = plt.subplots()
df[col1].plot(kind='bar', ax=ax)
df[col2].plot(ax=ax, marker='o', ls='-')
ax.legend(loc='best')

I expected to see a chart with both some bars and a line. However, what I end up with is only the line for df[col2], the bars from df[col1] are just not on the chart. Whatever is before df[col2] seem to have been overwritten.

I got around this with:

df[col1].plot(kind='bar', ax=ax, label=bar_labels)
ax.plot(df[col2], marker='o', ls='-', label=line_labels)
ax.legend(loc='best')

However, this isn't perfect as I had to use label tags otherwise legends will not included items for df[col2]...

Anyone out there has a more elegant solution to make both bars and lines show up?

** Edit ** Thanks to @DizietAsahi - Found out that this is a problem with DatetimeIndex as x-values. Filed the following at Pandas:

https://github.com/pydata/pandas/issues/10761#issuecomment-128671523

like image 785
WillZ Avatar asked Dec 20 '22 01:12

WillZ


1 Answers

I wonder if your problem is related to the hold state of your plot...

This works:

df = pd.DataFrame(np.random.random_sample((10,2)), columns=['col1', 'col2'])
fig, ax = plt.subplots()
plt.hold(True)
df['col1'].plot(kind='bar', ax=ax)
df['col2'].plot(ax=ax, marker='o', ls='-')
ax.legend(loc='best')

enter image description here

This only shows the line and not the bar plot

df = pd.DataFrame(np.random.random_sample((10,2)), columns=['col1', 'col2'])
fig, ax = plt.subplots()
plt.hold(False)
df['col1'].plot(kind='bar', ax=ax)
df['col2'].plot(ax=ax, marker='o', ls='-')
ax.legend(loc='best')

enter image description here

like image 184
Diziet Asahi Avatar answered Dec 26 '22 10:12

Diziet Asahi