#!/usr/bin/env python # coding: utf-8 # # 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() # * 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) # #### 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]") # #### 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]") # #### 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")