使用mpg
包中的ggplot2
数据我想应用facet_wrap()
保留随annotate()
添加的统计符号:
ggplot(mpg[ mpg$drv == levels(mpg$drv)[1] ,],
aes(x = class, y = hwy)) +
geom_boxplot() +
annotate("segment", x=2, xend=3, y= 26, yend = 26) +
annotate("text", x=2.5, y= 27, label = "*", size = 10)
ggplot(mpg[ mpg$drv == levels(mpg$drv)[2] ,],
aes(x = class, y = hwy)) +
geom_boxplot() +
annotate("segment", x=3, xend=4, y= 45, yend = 45) +
annotate("text", x=3.5, y= 46, label = "*", size = 10)
我尝试将每个绘图存储为一个对象并将其添加到空面。这是我能想到的唯一想法,但它没有成功:
ggplot(mpg, aes(x = class, y = hwy)) +
facet_wrap( ~ drv) +
plot1 + plot2
Error in p + o : non-numeric argument to binary operator
In addition: Warning message:
Incompatible methods ("+.gg", "Ops.data.frame") for "+"
非常感谢您的帮助, 塞尔吉奥
答案 0 :(得分:1)
不是使用注释,而是可以使用geom_text和geom_segment函数,它们允许将文本和段映射到其他变量,因此在不同的构面面板中具有不同的值。示例代码可能如下所示:
annote <- data.frame(x_cls = c(2.5, 3.5, 4.5), x_cls_end=c(3, 4, 5), y_hwy= c(26, 45, 55), y_hwy_end= c(26, 45, 55), drv = c("4", "f", "r") )
ggplot(mpg, aes(x = class, y = hwy)) +
geom_boxplot() +
geom_segment(data=annote, aes(x=x_cls, xend = x_cls_end, y= y_hwy, yend=y_hwy_end) ) +
geom_text(data=annote, aes(x=x_cls, y= y_hwy, label = "*"), size = 10) +
facet_wrap( ~ drv)