我如何用R在ggplot中写出显着性水平?

时间:2019-07-26 21:53:38

标签: r ggplot2 boxplot significance

我使用引导方法进行了分析。现在,我想在方框图中绘制“重要性”。但是我总是得到相同的错误消息: 错误:美学必须为长度1或与数据相同(18):颜色 有人能帮我吗? DataPlot_7是示例数据帧:

df1 <- data.frame(a = c(1, 1:2,2), b = c(60, 61, 61, 60))

DataPlot_7 <- data.frame(DeltaFace = c(48.58, 0.70, -1.54, 1.29, 64.29, 12.00, 60.87, 4.83), Manipulation = as.factor(c("positive", "neutral", "negative","negative","positive", "positive", "neutral","negativ")), Condition = as.factor(c("1", "2", "1", "2", "2", "1", "2", "1")))


Plot.Mean.Diff.Face.Manipulition_4 <- ggplot(data = DataPlot_7, aes(x = DataPlot_7$Condition, y = DataPlot_7$DeltaFace, color=DataPlot_7$Condition)) +
geom_boxplot(alpha = 0.6,outlier.colour = "#1F3552", outlier.shape = 20, width = 30)+
  facet_wrap(~Manipulation, ncol = 2)+
  scale_x_discrete(name = "X" ) +
  scale_y_continuous(name = "Y", breaks = seq(-100, 100, 25), limits=c(-100, 100)) + 
  ggtitle("title") +
  theme_set(theme_apa())+ 
  theme(plot.caption = element_text(hjust = 0.2),
    axis.title.x=element_blank(),
    axis.text.x=element_blank())+   
  scale_fill_brewer(palette = "Accent") + 
theme(legend.position="right")+ 
geom_line(data = df1, aes(x = a, y = b)) + annotate("text", x = 2.5, y = 62, label = "*", size = 8)


Plot1 <- Plot.Mean.Diff.Face.Manipulition_4

目标是从条件到条件获得一些水平线,如果有意义,我可以在该线上手动设置一个星星

我在StackOverflow上找到了这种方法,例如:

pp <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot()
df1 <- data.frame(a = c(1, 1:3,3), b = c(39, 40, 40, 40, 39))
pp + geom_line(data = df1, aes(x = a, y = b)) + annotate("text", x = 2, y = 42, label = "*", size = 8) 

但是每次我尝试将其更改为数据集时,我都会得到描述的错误消息。

1 个答案:

答案 0 :(得分:0)

在最初的ggplot()调用中设置美感时,默认情况下,它们将被后续图层继承。在这种情况下,您的color = Conditiongeom_line层继承,但是它使用的数据框没有Condition列。解决方案是在inherit.aes = FALSE层中设置geom_line

我已经进行了更改,从$内部删除了aes(),格式化了代码,删除了一些看起来不相关的主题选项,并且需要额外的软件包。我认为这可以解决所有问题。

ggplot(data = DataPlot_7, aes(x = Condition, y = DeltaFace, color = Condition)) +
  geom_boxplot(
    alpha = 0.6,
    outlier.colour = "#1F3552",
    outlier.shape = 20,
    width = 30
  ) +
  facet_wrap( ~ Manipulation, ncol = 2) +
  scale_x_discrete(name = "X") +
  scale_y_continuous(
    name = "Y",
    breaks = seq(-100, 100, 25),
    limits = c(-100, 100)
  ) +
  theme(
    plot.caption = element_text(hjust = 0.2),
    axis.title.x = element_blank(),
    axis.text.x = element_blank()
  ) +
  scale_fill_brewer(palette = "Accent") +
  geom_line(data = df1, aes(x = a, y = b), inherit.aes = FALSE) +
  annotate(
    "text",
    x = 2.5,
    y = 62,
    label = "*",
    size = 8
  )

enter image description here