Add facet_grid panel means as text and hline

前端 未结 1 1792
终归单人心
终归单人心 2021-01-21 00:59

I have a dataframe that looks like this.

> head(df)
  DGene JGene cdr3_len Sum
1 IGHD1 IGHJ1        0  22
2 IGHD1 IGHJ1        1  11
3 IGHD1 IGHJ1        2  1         


        
相关标签:
1条回答
  • 2021-01-21 01:35

    Here's a way to add both text and a vertical line for the mean of cdr3_len by pre-computing the desired values (per @jwillis0720's comment):

    First, calculate the mean of cdr3_len for each panel and then left_join that data frame to a second data frame that calculates the appropriate y-value for placing the text on each panel (because the appropriate y-value varies only by level of JGene).

    library(dplyr) 
    
    meanData = df %>% group_by(JGene, DGene) %>%
      summarise(meanCDR = sum(Sum*cdr3_len)/sum(Sum)) %>%
      left_join(df %>% group_by(JGene) %>%
                  summarise(ypos = 0.9*max(Sum)))
    

    Now for the plot:

    ggplot(df,aes(x=cdr3_len, y=Sum)) +
      geom_vline(data=meanData, aes(xintercept=meanCDR), colour="red", lty=3) +
      geom_line() +
      geom_text(data=meanData, 
                aes(label=round(meanCDR,1), x=40, y=ypos), colour="red",
                hjust=1) +
      xlim(c(1,42)) + 
      facet_grid(JGene~DGene,scales="free_y")
    

    0 讨论(0)
提交回复
热议问题