2015-03-02 136 views
0

我想繪製一個帶有點的「組合」條形圖。 考慮到以下虛擬數據:組合條形圖和ggplot2中的點

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

回答

4

您可以添加圖層在一起,但如果他們有不同的數據和/或美學你要包括每個圖形層中的參數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))

+0

或'geom_point(數據= mtcars,AES(Y = DISP,X = CYL-.5,補= CYL))'以獲得所需的偏移。 – lukeA 2015-03-02 21:05:35

1

您可以分別指定每個圖層到ggplot2。通常,您對每個geom都使用相同的數據框和選項,因此在ggplot()中設置默認值是有意義的。在你的情況,你應該分別指定每個GEOM:

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