2

The following code works and gives this plot.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame(data=np.random.randn(100, 4), index=pd.DatetimeIndex(start='2016', freq='D', periods=100),
                  columns=['A', 'B', 'C', 'D'])

df['total'] = df[['A', 'B', 'C', 'D']].sum(axis=1)
fig, ax = plt.subplots(2,1)
df[['A', 'B', 'C', 'D']].plot(kind='bar', ax=ax[0], stacked=True)
df[['total']].plot(ax=ax[1])

2 plots

what I would like to have is the line and stacked bar on the same plot.

So far I tried this piece of code but neither the line nor the bars are displayed depending on the order I call them :

fig, ax = plt.subplots(1,1)
df[['A', 'B', 'C', 'D']].plot(kind='bar', ax=ax, stacked=True)
df[['total']].plot(ax=ax)
plt.show()

1 plot but bars not displayed

i guess i have an issue with the x axis, not sure though

EDIT:

the following piece of code and graph associated tends to confirm I got something happening with the axis:

fig2, ax2 = plt.subplots()
df2 = pd.DataFrame(data=np.random.randn(100, 4), columns=['A', 'B', 'C', 'D'])
df2['total'] = df2[['A', 'B', 'C', 'D']].sum(axis=1)
print(df2.head(5))

df2[['A', 'B', 'C', 'D']].plot(kind='bar', stacked=True, ax=ax2)
df2['total'].plot('line', color='orange', linewidth=2.0, ax=ax2)

working without date index

euri10
  • 2,446
  • 3
  • 24
  • 46
  • I tried plotting your original dataframe without setting the `DatetimeIndex` as index and it works, so maybe the issue is related to that. – Fabio Lamanna Feb 16 '16 at 13:45
  • 1
    as a possible workaround, you can try to modify the index to strings with `df.index = df.astype(np.str)` – Fabio Lamanna Feb 16 '16 at 13:48
  • that effectively solves partially the issue, partially because now the axis labels are 'ugly' :) maybe I'll work from there if nothing better comes up – euri10 Feb 16 '16 at 13:51
  • I think this should be a bug, in case consider open an issue [here](https://github.com/pydata/pandas/issues). – Fabio Lamanna Feb 16 '16 at 13:52
  • 1
    Possibly relevant: http://stackoverflow.com/questions/30133280/pandas-bar-plot-changes-date-format – tmdavison Feb 16 '16 at 14:49
  • very relevant indeed, dunno if I post a bug or not, kind='bar' creates a FixedFormatter that is 'deleted' by the line that creates a pandas.tseries.converter.TimeSeries_DateFormatter – euri10 Feb 16 '16 at 15:25
  • more digging and found a hack thanks to this : https://github.com/pydata/pandas/issues/10761#issuecomment-128671523 – euri10 Feb 16 '16 at 15:47

0 Answers0