簡體   English   中英

組合條形圖和ggplot2中的點

[英]Combined bar plot and points in 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))

最終圖應如下所示: 樣例

您可以將圖層添加在一起,但是如果它們具有不同的數據和/或美觀,則需要在每個圖形圖層中包含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))

您可以將每個圖層分別指定給ggplot2 通常,每個geom使用相同的數據框和選項,因此在ggplot()設置默認值ggplot() 在您的情況下,您應該分別指定每個幾何:

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