4.3.1 Stacked Chart
It's very important to choose the proper chart to illustrate the composition. There are some tips:
If the change is over time, consider a stacked chart.
If only a few periods and only presents relative differences, use a stacked 100% column chart.
If only a few periods and presents relative and absolute differences, use a stacked column chart.
If it has many periods and presents relative differences, use a stacked 100% area chart.
if it has many periods and presents relative and absolute differences, use a stacked area chart.
1. Stacked 100% Column Chart
Let's create a fruit sales dataset and calculate each items' percentage.
raw = {'time':['Q1','Q2','Q3','Q4'],
'apple':[1000,2000, 1550, 1800],
'banana':[3000,4000, 3300, 2000],
'kiwi':[500, 1200, 2800, 1500]}
df = pd.DataFrame(raw)
# From value to percentage
total = [i+j+k for i,j,k in zip(df['apple'], df['banana'], df['kiwi'])]
apple = [i / j * 100 for i,j in zip(df['apple'], total)]
banana = [i / j * 100 for i,j in zip(df['banana'], total)]
kiwi = [i / j * 100 for i,j in zip(df['kiwi'], total)]
plt.figure(figsize = (12,8))
sns.barplot(time, apple, color='salmon',label = 'Apple')
sns.barplot(time, banana, color='gold',bottom = apple, label = 'Banana')
sns.barplot(time, kiwi, color='lightgreen', bottom=[i+j for i,j in zip(apple, banana)],label = 'Kiwi')
plt.legend(ncol=3, loc="best", frameon=True)

2. Stacked Column Chart
plt.figure(figsize = (12,8))
sns.barplot(x="time", y="apple",data = fruit, label="Apple",
color="salmon")
sns.barplot(x="time", y="banana",data = fruit, label="Banana",
color="gold",alpha = 0.5)
sns.barplot(x="time", y="kiwi", data = fruit,label="Kiwi",
color="lightgreen",alpha = 0.5)
plt.legend(ncol=1, loc="best", frameon=True)

3. Stacked 100% Area Chart
plt.figure(figsize = (12,8))
plt.stackplot(time, apple, banana,kiwi , labels=['Apple','Banana','Kiwi'])
plt.legend(loc='best')
plt.margins(0,0)
plt.title('100 % stacked area chart')
plt.show()

4. Stacked Area Chart
plt.figure(figsize = (12,8))
plt.stackplot(time,[fruit['apple'],fruit['banana'],fruit['kiwi']], labels=['Apple','Banana','Kiwi'] )
plt.legend(loc='upper right')
plt.title('Stacked area chart')
plt.show()

Last updated
Was this helpful?