简体   繁体   English

组合条形图和ggplot2中的点

[英]Combined bar plot and points in ggplot2

I would like to plot a "combined" bar plot with points. 我想绘制一个带有点的“组合”条形图。 Consider to following dummy data: 考虑以下虚拟数据:

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))

The final plot should look like that: 最终图应如下所示: 样例

You can add layers together, but if they have different data and/or aesthetics you'll want to include the data and aes arguments in each graphical layer. 您可以将图层添加在一起,但是如果它们具有不同的数据和/或美观,则需要在每个图形图层中包含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()

If you want to make it so that the the points are off to the side of the bars, you could subtract an offset from the cyl values to move over the points. 如果要使这些点偏离条形图的侧面,则可以从圆柱值中减去一个偏移量以在这些点上移动。 Like @LukeA mentioned, by changing the geom_point to geom_point(data=mtcars, aes(y=disp, x=cyl-.5, fill=cyl)) . 就像提到的@LukeA一样,通过将geom_point更改为geom_point(data=mtcars, aes(y=disp, x=cyl-.5, fill=cyl))

You can specify each layer individually to ggplot2 . 您可以将每个图层分别指定给ggplot2 Often you are using the same data frame and options for each geom, so it makes sense to set defaults in ggplot() . 通常,每个geom使用相同的数据框和选项,因此在ggplot()设置默认值ggplot() In your case you should specify each geom separately: 在您的情况下,您应该分别指定每个几何:

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

se <- function(x){sd(x)/sqrt(length(x))}
my_dat <- summarise(group_by(mtcars, cyl),
                    my_mean = mean(disp),
                    my_se = se(disp))
p1 <- 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), stat="identity", width=0.75) + 
  geom_point(data = mtcars, aes(y = disp, x = cyl, fill = cyl)) +
  theme_classic() + ylim(c(0,500))

p1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM