Horizontal error bars and vertical "dodge"

geom_errorbar() can be plotted horizontally by assigning y,xmin,xmax aesthetics. The height of the error bar is defined by the height.

New type of position adjustment 'dodgev' is used to adjust the position by dodging overlaps to the side. Function position_dodgev(height) allows to set the dodge height.

In [1]:
from lets_plot import *
LetsPlot.setup_html()

1. The "Tooth Growth" Dataset

The ToothGrowth dataset describes the effect of Vitamin C on tooth growth in guinea pigs. Each animal received one of three dose levels of vitamin C (0.5, 1, and 2 mg/day) by one of two delivery methods: orange juice (OJ) or ascorbic acid (VC).

In [2]:
import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/ToothGrowth.csv")
df.head()
Out[2]:
len supp dose
0 4.2 VC 0.5
1 11.5 VC 0.5
2 7.3 VC 0.5
3 5.8 VC 0.5
4 6.4 VC 0.5
  • len : Tooth length
  • dose : Dose in milligrams (0.5, 1, 2)
  • supp : Supplement type (VC or OJ)

Let's calculate the mean value of tooth length in each group, minimum and maximum values, and use these information to plot error bars.

In [3]:
import numpy as np

data = {}

for supp_lvl in np.unique(df['supp']):
    for dose_lvl in np.unique(df['dose']):
        data_to_sum = df[(df['supp'] == supp_lvl) & (df['dose'] == dose_lvl)]

        mean = data_to_sum['len'].mean()
        len_min =  data_to_sum['len'].min()
        len_max = data_to_sum['len'].max()

        data.setdefault('supp', []).append(supp_lvl)
        data.setdefault('dose', []).append(dose_lvl)
        data.setdefault('length', []).append(mean)
        data.setdefault('len_min', []).append(len_min)
        data.setdefault('len_max', []).append(len_max)
        
pd.DataFrame(data)        
Out[3]:
supp dose length len_min len_max
0 OJ 0.5 13.23 8.2 21.5
1 OJ 1.0 22.70 14.5 27.3
2 OJ 2.0 26.06 22.4 30.9
3 VC 0.5 7.98 4.2 11.5
4 VC 1.0 16.77 13.6 22.5
5 VC 2.0 26.14 18.5 33.9

2. Error Bars without a Position Adjustment

In [4]:
ggplot(data) + \
    geom_errorbar(aes(y='dose', xmin='len_min', xmax='len_max', color='supp'), height=0.2, size=1.2) + \
    scale_color_brewer(palette="Set1") + \
    labs(x="Tooth length [mm]")
Out[4]:

3. Error Bars with position = 'dodgev'

To fix errorbars overlapping, use position_dodgev(height) - to move them vertically.

In [5]:
ggplot(data) + \
    geom_errorbar(aes(y='dose', xmin='len_min', xmax='len_max', color='supp'), height=0.2, size=1.2,
                  position=position_dodgev(0.4)) + \
    scale_color_brewer(palette="Set1") + \
    labs(x="Tooth length [mm]")
Out[5]:

4. Error Bars on Bar Plot

In [6]:
ggplot(data, aes(y='dose')) + \
    geom_bar(aes(x='length', fill='supp'), stat='identity', position='dodge', orientation='y') + \
    geom_errorbar(aes(xmin='len_min', xmax='len_max', group='supp'), height=0.2, size=1.2,
                position=position_dodgev(0.9)) + \
    scale_fill_brewer(palette="Paired")
Out[6]: