gpt4 book ai didi

r - ggplot2中的组合条形图和点

转载 作者:行者123 更新时间:2023-12-05 08:43:31 28 4
gpt4 key购买 nike

我想绘制一个带点的“组合”条形图。考虑以下虚拟数据:

library(ggplot2)
library(gridExtra)
library(dplyr)

se <- function(x){sd(x)/sqrt(length(x))}

p1 <- ggplot(mtcars, aes(y=disp, x=cyl, fill=cyl))
p1 <- p1 + geom_point() + theme_classic() + ylim(c(0,500))

my_dat <- summarise(group_by(mtcars, cyl), my_mean=mean(disp),my_se=se(disp))

p2 <- ggplot(my_dat, aes(y=my_mean,x=cyl,ymin=my_mean-my_se,ymax=my_mean+my_se))
p2 <- p2 + geom_bar(stat="identity",width=0.75) + geom_errorbar(stat="identity",width=0.75) + theme_classic() + ylim(c(0,500))

最终的情节应该是这样的: example plot

最佳答案

您可以将层添加在一起,但如果它们具有不同的数据和/或美学,您需要在每个图形层中包含 dataaes 参数。

p3 <- ggplot() +
geom_bar(data=my_dat, aes(y=my_mean,x=cyl,ymin=my_mean-my_se,ymax=my_mean+my_se), stat="identity", width = 0.75) +
geom_errorbar(data=my_dat, aes(y=my_mean,x=cyl,ymin=my_mean-my_se,ymax=my_mean+my_se), width = 0.75) +
geom_point(data=mtcars, aes(y=disp, x=cyl, fill=cyl)) +
ylim(c(0,500)) +
theme_classic()

如果你想让点偏离条形的一侧,你可以从圆柱值中减去一个偏移量来移动这些点。就像@LukeA 提到的那样,通过将 geom_point 更改为 geom_point(data=mtcars, aes(y=disp, x=cyl-.5, fill=cyl))

关于r - ggplot2中的组合条形图和点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28819135/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com