将条形图与箱形图组合成一个图形

时间:2016-09-05 13:00:52

标签: r boxplot

我有以下barplot和boxplots:

barplot

boxplots

我需要将它们组合成一个图。我该怎么办?

我尝试将add = TRUE用于boxplots命令行,但它们不合适。

2 个答案:

答案 0 :(得分:1)

以下是使用mtcars数据集来说明重叠图的示例:

library(ggplot2)
library(dplyr)

temp <- mtcars %>% group_by(cyl = factor(cyl)) %>% summarise(mpg = mean(mpg))
ggplot(mtcars, aes(factor(cyl), mpg)) + geom_bar(data = temp, aes(cyl, mpg), stat = "identity") + geom_boxplot()

enter image description here

答案 1 :(得分:0)

R基地,您可以尝试:

library(ggplot2) # load data as in the ggplot2 answer 

# calculate the data for the barplot, here the mean mpg-value per cylinder 
# using aggregate
b <- aggregate(mtcars$mpg, list(mtcars$cyl), mean)

# plot the barplot, save the x-axis position of each bar in n 
n <- barplot(as.matrix(b)[,2], names.arg = b$Group.1, ylim=c(0, max(mtcars$mpg) + 10))
n
     [,1]
[1,]  0.7
[2,]  1.9
[3,]  3.1

# plot the boxplot using add=TRUE 
# and the "at" argument for the x-axis positions which are saved in n
boxplot(mtcars$mpg ~ mtcars$cyl, at= n, add=TRUE),

enter image description here