Reputation: 242
I need to create a chart like the one below, a series of stacked bars. Some values are positive and some are negative. I would like the chart to be displayed just like the stacked bar chart from excel, which stacks positives values up and negative values down. Is there a straightforward method to do this for N number of categories?
Here is some example data:
df = pd.DataFrame(index=['06-11-2018', '06-12-2018', '06-13-2018', '06-14-2018', '06-15-2018'],
data={'A': [-378, -2347, 509, 987, 513],
'B': [-527, -2599, 765, 533, 670],
'C': [-2343, -2273, 2093, 2197, 1990],
'D': [-1845, -1853, 3325, 1306, 2160]})
Upvotes: 0
Views: 11621
Reputation: 991
The data frame's plot
function handles negative values in the way you describe. If we change some of the values in the data frame to be negative the line
df.plot(kind="bar", stacked=True)
gives us this chart:
We can add a 'total' line similar to the black line in the question's image by summing the rows of the data frame and plotting the returned Series
object on the same axes
as the bar chart:
The code that generated this second chart is below.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(index=['06-11-2018', '06-12-2018', '06-13-2018',
'06-14-2018', '06-15-2018'],
data={'A': [-378, 2347, 509, 987, 513],
'B': [527, 2599, -765, 533, 670],
'C': [2343, -2273, 2093, -2197, 1990],
'D': [1845, 1853, -3325, 1306, 2160]})
ax = df.plot(kind="bar", stacked=True)
df.sum(axis=1).plot(ax=ax, color="k")
plt.show()
Upvotes: 5