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.
from lets_plot import *
LetsPlot.setup_html()
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).
import pandas as pd
df = pd.read_csv("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/ToothGrowth.csv")
df.head()
Let's calculate the mean value of tooth length in each group, minimum and maximum values, and use these information to plot error bars.
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)
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]")
position = 'dodgev'¶To fix errorbars overlapping, use position_dodgev(height) - to move them vertically.
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]")
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")