Plotnine (ggplot) : Add whisker to end of geom_segment

Question:

I am doing this in python’s wonderful plotnine package, but hoping ggplotters may have a solution as well.

Consider the following data and plot:

df = pd.DataFrame({
    'label' : ['A','B','C','D'], 
    'start' : [1, 1.5, 2.5, 1.75], 
    'end' : [3.85, 2.75, 4.25, 3], 
})
    
p = (ggplot(df, aes(x='label', xend='label', y='start', yend='end'))
  + theme_light()
  + geom_segment()
  + coord_flip()
  + labs(x=None,y=None)
)
p

enter image description here

I would like the segments to end with a whisker or a ‘T’. Kind of like:

enter image description here

Can this be done? I have only seen information for arrows (which don’t have a ‘T’ option as far as I can tell).

Asked By: brb

||

Answers:

Not sure about and not aware of any option to achieve that via arrow. But one option would be to add your whiskers using a second geom_segment for which I add a helper column with the numeric position of the y axis labels:

import pandas as pd
from plotnine import *

df = pd.DataFrame({
    'label' : ['A','B','C','D'], 
    'start' : [1, 1.5, 2.5, 1.75], 
    'end' : [3.85, 2.75, 4.25, 3]
})
df['label_num'] = [1, 2, 3, 4]

p = (ggplot(df, aes(x='label', xend='label', y='start', yend='end'))
    + theme_light()
    + geom_segment()
    + geom_segment(aes(y = 'start', yend='start', x = 'label_num - .1', xend = 'label_num + .1'))
    + coord_flip()
    + labs(x=None,y=None))

p

enter image description here

Answered By: stefan

In R / ggplot2, at least, you would use geom_errorbar() instead of geom_segment():

library(ggplot2)

df <- data.frame(
    'label' = c('A','B','C','D'),
    'start' = c(1, 1.5, 2.5, 1.75), 
    'end' = c(3.85, 2.75, 4.25, 3)
)
    
p <- ggplot(df, aes(x=label, ymin=start, ymax=end)) +
  theme_light() +
  geom_errorbar(width = 0.1) +
  coord_flip() +
  labs(x=NULL,y=NULL)

p

Note (1) use of ymin / ymax instead of y / yend, and (2) use of width argument to adjust crossbar size.

Answered By: zephryl
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.