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
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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With