Home > Software engineering >  Separate geom_linerange by group within a facet in ggplot
Separate geom_linerange by group within a facet in ggplot

Time:11-16

Let's say I have the following data:

test = read.table(text = 'condition1 condition2 estimate std_error name
a x .466 .09 name_1
a y .343 .131 name_1
b x .466 .09 name_1
b y .343 .131 name_1
a x .466 .09 name_2
a y .343 .131 name_2
b x .466 .09 name_2
b y .343 .131 name_2', header = T, stringsAsFactors = T)


ggplot(data = test, aes(x = estimate, y = condition1, fill = condition2, group = condition2))  
    geom_point(color = 'black')  
    geom_linerange(aes(xmin = estimate - std_error,
                       xmax = estimate   std_error), color = 'black')  
    ylab(NULL)  
    facet_grid(name ~ .,
               scales = "free_y",
               space = "free_y",
               switch = 'y')

enter image description here

I'm trying to separate out the x and y lines as separate lines within the b and a conditions within a given facet (name_1 and name_2). But my code as is is putting the two lines as the same y-value, so they're overlapping. What is the best way to separate the lines?

CodePudding user response:

Adjust width = X to taste.

...
 geom_point(color = 'black', position = position_dodge(width = 1))  
  geom_linerange(aes(xmin = estimate - std_error,
                     xmax = estimate   std_error), color = 'black',
                     position = position_dodge(width = 1))  
...

enter image description here

Or here with some more aesthetic tweaks:

ggplot(data = test, aes(x = estimate, y = condition1, fill = condition2, group = condition2))  
  geom_linerange(aes(xmin = estimate - std_error,
                     xmax = estimate   std_error), color = 'black',
                 position = position_dodge(width = 0.5))  
  geom_point(color = 'black', size = 2, shape = 21, position = position_dodge(width = 0.5))  
  ylab(NULL)  
  facet_grid(name ~ .,
             scales = "free_y",
             space = "free_y",
             switch = 'y')  
  theme(panel.grid.major.y = element_blank())

enter image description here

  • Related