尝试将额外的geoim_point图层添加到ggplot lineplot

时间:2017-10-05 12:53:30

标签: r ggplot2

我正在尝试使用以下代码制作折线图:

    ggplot(out2, aes(factor(out2$term, levels=unique(as.character(out2$term)) ),estimate, group = 1)) +
        geom_line(aes(group = 1), size = 1.2) + 
        mytheme2 + 
        geom_point(shape = 21, colour = "black", fill = "white", size = 5, stroke = 2) + 
        scale_shape(solid = FALSE) + 
        theme(axis.text.x = element_text(angle = 50, hjust = 1, size = 15, family = "serif")) + 
        scale_x_discrete(labels = labels1) + 
        theme(plot.title = element_text(hjust = 0.5)) + 
        geom_ribbon(data=out2,aes(ymin=conf.low,ymax=conf.high),alpha=0.1)

这给了我这张图:

enter image description here

但是,基于名为p.val的数据框中的变量,如果p.val的值小于.05,我想添加一个星号,如果值小于.001,则添加两个星号。 。

我尝试在代码底部添加一行来实现此目的:

    ggplot(out2, aes(factor(out2$term, levels=unique(as.character(out2$term)) ),estimate, group = 1)) +
        geom_line(aes(group = 1), size = 1.2) + 
        mytheme2 + 
        geom_point(shape = 21, colour = "black", fill = "white", size = 5, stroke = 2) + 
        scale_shape(solid = FALSE) + 
        theme(axis.text.x = element_text(angle = 50, hjust = 1, size = 15, family = "serif")) + 
        scale_x_discrete(labels = labels1) + 
        #labs(y= "Standardized regression coefficient", x = "TAT threshold (Lux) minutes") + 
        #labs(title = "Sensitivity Analyses showing standardized regression coefficients for models with a range of \nTAT Light Thresholds (lux), Sleep Quality, Activity Level and BMI predicting T1 Hyperactivity.") + 
        theme(plot.title = element_text(hjust = 0.5)) + 
        geom_ribbon(data=out2,aes(ymin=conf.low,ymax=conf.high),alpha=0.1) +
        geom_point(data=out2[out2$p.value > 0.05,], color="red", size=3)

然而,这给了我错误信息:

Error: Aesthetics must be either length 1 or the same as the data (6): x, y, group

1 个答案:

答案 0 :(得分:0)

您正在将数据框传递到最后geom_point()图层,该图层是原始out2的较小子集,而ggplot不知道如何分发此缩短的数据跨越原始较大的数据,从而发出警告。

如果您先在数据框中为重要性标签构建了一个列,然后使用geom_text()将其分层而不是geom_point(),则可能会更容易。

out2$signif_label <- ifelse(out2$p.value < .05, "*", "")
out2$signif_label <- ifelse(out2$p.value < .001, "**", out2$signif_label)

然后添加此项而不是最后一次geom_point()

geom_text(aes(label = signif_label), color = "red", size = 3)

如果您在初始data电话中分配ggplot(data = ,...),那么所有后续图层都会尝试继承相同的数据,因此我们不需要再次分配,除非它&#39;与众不同。