0

I have a data set in a pandas dataframe:

dfc

    a   b   c   d
0   5.1 3.5 1.4 -0.4
1   4.9 3   1.4 -0.4
2   4.7 3.2 1.3 -0.4
3   4.6 3.1 1.5 -0.4
4   5   3.6 1.4 -0.4
5   5.4 3.9 1.7 -0.8
6   4.6 3.4 1.4 -0.6
7   5   3.4 1.5 0.4
8   4.4 2.9 1.4 0.4
9   4.9 3.1 1.5 0.2

I've been trying to build a stacked bar chart that looks like below. The added complication is that there may be different numbers of columns on this chart (there might be columns 'e' and 'f' for example).

I've been trying to build a loop to go through the columns and apply them to the chart.

No luck yet.

cumval=0
fig = plt.figure(figsize=(15,6))
for col in dfc.columns[~dfc.columns.isin(['Model',yname])]:
    plt.bar(dfc.index.values, dfc[col], bottom=cumval, label=col)
    cumval = (cumval+dfc[col])

plt.plot(dfc['Model'],'b-o',label='Model')
plt.plot(dfc[yname],'r-o',label='Acutal')    

_ = plt.xticks(rotation=30)
_ = plt.legend(fontsize=8)

Anyone have any ideas?

enter image description here

fred.schwartz
  • 2,023
  • 4
  • 26
  • 53
  • If there are columns `e` and `f` then what's wrong with trying `columns=['a','b','c','d','e','f']`? The above answer by the way loops through the columns so you don't have to specify them manually. Give it a try and post a reproducible code if necessary – Sheldore Sep 21 '18 at 15:50
  • This has worked perfectly. The only problem is for columns with negative values are coming out as positive? – fred.schwartz Sep 21 '18 at 16:18
  • 1
    Please share a working code which reproduces your problem. It's easy to play around with the code then and find the problem – Sheldore Sep 21 '18 at 16:21
  • sure. updated :) – fred.schwartz Sep 21 '18 at 16:27
  • 1
    Ok, could you for once try [this](https://stackoverflow.com/questions/35979852/stacked-bar-charts-using-python-matplotlib-for-positive-and-negative-values) already provided SO answer and let us know if it addresses your issue. You will have to adapt it to make it work with pandas. And also, you wrote "negative values are coming out as positive". I don't understand this. The negative values are coming out in the plot as negative. What is the final figure you want to have like? – Sheldore Sep 21 '18 at 16:31
  • 2
    `df.plot(kind='bar', stacked=True)` – user3483203 Sep 21 '18 at 16:48

0 Answers0