将ggplot facet_wrap与geom_segment结合使用以在散点图中绘制平均线

时间:2017-08-10 14:55:34

标签: r ggplot2

可重复的例子

df包含A,B

的分组数据
library(tidyverse)
set.seed(1)
df <- data.frame(A=rep(c("good","bad"),each=8),
                 B=rep(c("yes","no"),4),
                 C=sample(1:20,16),
                 stringsAsFactors=F) %>%
                 group_by(A,B)

 #      A     B     C
 #1  good   yes    13
 #2  good    no     2
 #3  good   yes     4
 #4  good    no    18
 # etc

summ包含群组A,B

的摘要数据
summ <- df %>%
          summarise(mean = mean(C),
                    median = median(C)) %>%
          gather(variable, value, mean:median)

#      A     B variable value
#1   bad    no     mean 13.50
#2   bad   yes     mean 11.00
# etc

问题

我想绘制每个散点图的均值和中线,但与facet_wrap结合使用。 我在未使用facet_wrap时遇到了很多答案。

我可以画线但是对齐有问题。您可以通过运行此代码来查看问题

ggplot(df, aes(x=B, y=C)) +
  geom_violin() +
  geom_point() +
  geom_segment( data = summ,
    aes(x = as.numeric(interaction(A,B)) - 0.5,
        xend = as.numeric(interaction(A,B)) + 0.5,
        y = value, yend = value, colour = variable ) ) +
  facet_wrap(~A, nrow=1) +
  theme_classic() + 
  theme( axis.text = element_text( size = 14 ),
         axis.text.x = element_text( size = 20 ),
         axis.title = element_text( size = 16, face = "bold" ),
         legend.position="none" )

1 个答案:

答案 0 :(得分:3)

如果我正确理解了这个问题,那么需要改变的只是geom_segment(...)中的一点。而不是as.numeric(interaction(A,B)),写下as.numeric(as.factor(B)

ggplot(df, aes(x=B, y=C)) +
  geom_violin() +
  geom_point() +  
  geom_segment(data=summ,aes(x = as.numeric(as.factor(B)) - 0.5, 
                   xend = as.numeric(as.factor(B)) + 0.5, 
                   yend = value, 
                   y = value, 
                   colour = variable)) +
  facet_wrap(~A, nrow=1) +
  theme_classic() + 
  theme( axis.text = element_text( size = 14 ),
         axis.text.x = element_text( size = 20 ),
         axis.title = element_text( size = 16, face = "bold" ),
         legend.position="none" )

enter image description here