A34 Stacked Bar Chart - cimat/data-visualization-patterns GitHub Wiki

#A 3.4: STACKED BAR CHART

Description

In a stacked bar chart, each bar represents a whole set quantitative data. A bar is then separated into segments so that each segment represents a single item of the corresponding set. Stacked bar charts are therefore an alternative representation for quantitative multiset data (Behrens, 2008).

Required Data

Use the stacked bar chart to display multiple sets of quantitative values. The sets all share the same scaling, i.e. each set has the same number and types of values the single values of two different sets are directly comparable to each other (Behrens, 2008).

Usage

Create a Cartesian coordinate grid and draw the first series of datasets as in a stacked bar chart. Apply the second series of patterns by creating the respective rectangles and “stacking” them on top of their corresponding counterparts from the previous series. Repeat with all subsequent datasets (Behrens, 2008).

Rationale

Stacked bar charts let the user directly compare the total magnitude of several datasets within one diagram while providing additional information about the composition of these sets from their single items. The value of a whole dataset is the most important information to retrieve from this visualization - the magnitude of single items can be read and interpreted, but their precise evaluation is hampered because the segments of a bar do not share the same base (Behrens, 2008).

Related Patterns

  • A 3.1 Simple Bar Chart
  • A 3.3 Dot Matrix
  • A 3.5 Isometric Bar Chart
  • A 4.1 Simple Pie Chart
  • A 4.2 Ring Chart

PYTHON IMPLEMENTATION

Data Set

from datos import data
d=data('mtcars')
d.head()

Dependences

  • Matplotlib
  • Seaborn
  • Pyqtgraph
  • Pandas

Code Example

Matplotlib

import numpy as np
import matplotlib.pyplot as plt
from datos import data
import pandas

d=data('mtcars')
t1 = d.pivot_table( values = 'carb',index=['cyl'], columns = ['gear'],
aggfunc = len)
bar_width = 0.4
opacity = 0.4
rects1 = plt.bar(t1.columns, t1.values[0], bar_width,
alpha=opacity,color='g',)
rects2 = plt.bar(t1.columns, t1.values[1], bar_width, alpha=opacity,
color='r', bottom=t1.values[0])
rects3 = plt.bar(t1.columns, t1.values[2], bar_width, alpha=opacity,
color='y', bottom=t1.values[0]+t1.values[1])
plt.xlabel('Number of Gears')
plt.ylabel('Frequency')
plt.title('Car Distribution by Gear and Cylindres')
plt.legend(t1.index, title='Cylindres')
plt.show()

{width=12 cm}

Seaborn

import seaborn as sns
import matplotlib.pyplot as plt
from datos import data
import pandas

sns.set(style="whitegrid")
f, ax = plt.subplots(figsize=(6, 15))
d=data('mtcars')
t1 = d.pivot_table( values = 'carb',index=['cyl'], columns = ['gear'],
aggfunc = len)
bar_width = 0.4
sns.barplot(x=t1.columns, y=t1.values[0]+t1.values[1]+t1.values[2],
label="8 ", color="#2ecc71")
sns.barplot(x=t1.columns, y=t1.values[0]+t1.values[1],  label="6 ",
color="salmon")
sns.barplot(x=t1.columns, y=t1.values[0],  label="4 ",
color="skyblue")
ax.legend(ncol=1, loc="center right",title="Cylindres")
sns.despine(bottom=True)
plt.title('Car Distribution by Gear and Cylindres', family='Serif',
size=16)
plt.show()

{width=12 cm}

Pyqtgraph

from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import numpy as np
from datos import data
import pandas

d=data('mtcars')
t1 = d.pivot_table( values = 'carb',index=['cyl'], columns = ['gear'],
aggfunc = len)
bar_width = 0.25
win = pg.plot(title='Simple Bar Chart')
bg1 = pg.BarGraphItem(x=t1.columns,
height=t1.values[2]+t1.values[1]+t1.values[0], width=bar_width,
brush='g')
bg2 = pg.BarGraphItem(x=t1.columns, height=t1.values[1]+t1.values[0],
width=bar_width, brush='r')
bg3 = pg.BarGraphItem(x=t1.columns, height=t1.values[0],
width=bar_width, brush='y')
win.addItem(bg1)
win.addItem(bg2)
win.addItem(bg3)
win.setTitle('Car Distribution by Gear and Cylindres ')
win.setLabel('left', "Frequency", )
win.setLabel('bottom', "Number of Gears")

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore,
'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()

{width=12 cm}

References

R IMPLEMENTATION

Data Set

counts <- table(mtcars$cyl, mtcars$gear)
counts

##    
##      3  4  5
##   4  1  8  2
##   6  2  4  1
##   8 12  0  2

Dependences

  • lattice
  • ggplot2

Code Example

Graphics

counts <- table(mtcars$cyl, mtcars$gear)
barplot(counts, main="Car Distribution by Gears and Cyl",
  xlab="Number of Gears", ylab="Frequency", col=c("skyblue","gray","green"),
    legend = rownames(counts), beside=FALSE)

Lattice

library("lattice")
counts <- table(mtcars$gear, mtcars$cyl)
barchart(counts, stack = TRUE, horizontal="false", main="Car Distribution by Gears and Cyl",     xlab="Number of Gears", ylab="Frequency", 
         auto.key = list(space="top", columns=3, title="Cylindres", cex.title=1))

ggplot2

library("ggplot2")

## Warning: package 'ggplot2' was built under R version 3.2.2

g <- ggplot(mtcars, aes(factor(gear), fill=factor(cyl))) + geom_bar( position = "fill")
g + labs(list(title = "Car Distribution by Gears and Cyl", x="Number of Gears", y="Frequency"))

References

⚠️ **GitHub.com Fallback** ⚠️