Lijia Yu
Lijia Yu

Reputation: 90

ggplot2: add horizontal line by group inside facet_grid

I want to draw a dot plot with horizontal lines by groups. The df object store the points and the df.line object stores the line I want to add to the dot plot. The horizontal lines are not the mean/median value of points, they are some standards I want to show in this figure.

I tried gome_hline, geom_line, geom_errorbar, and stat_summary. but none of them work as I want.

Could anyone teach me how to do it?

library(ggplot2)
library(tidytext)
set.seed(42)
df=data.frame(site=c(rep("a",5),rep("b",5),rep("c",5)),
          sample=c(1:5,1:5,1:5),
          value=c(runif(5, min=0.54, max=0.56),runif(5, min=0.52, max=0.6),runif(5, 
          min=0.3, max=0.4)),
          condition=c(rep("c1",5),rep("c2",5),rep("c2",5)))
df.line=data.frame(site=c("a","b","c"),standard=c(0.55,0.4,0.53))
ggplot(df)+
geom_point(aes(x=tidytext::reorder_within(site,value,condition,fun=mean),
                       y=value))+
facet_grid(~condition,space="free_x",scales = "free_x")+
scale_x_reordered()

img

Upvotes: 4

Views: 920

Answers (1)

Ian Campbell
Ian Campbell

Reputation: 24810

First, merge df and df.line together. Next, move the main aes() call to ggplot so it can be used later. Then use stat_summary:

library(dplyr)
merge(df,df.line) %>%
ggplot(aes(x=tidytext::reorder_within(site,value,condition,fun=mean),
                       y=value))+
geom_point()+
stat_summary(aes(y = standard, ymax = after_stat(y), ymin = after_stat(y)),
             fun = mean, geom = "errorbar", color = "red", width = 0.3) +
facet_grid(~condition,space="free_x",scales = "free_x")+
scale_x_reordered()

enter image description here

Upvotes: 3

Related Questions