将条形图与箱线图组合成一个图形
Combine barplot with boxplots into a single figure
我得到了以下条形图和箱线图:
我需要将它们组合成一个图形。我该怎么做?
我尝试在箱形图命令行中使用 add = TRUE
,但它们不合适。
这是一个使用 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()
在基地 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),
我得到了以下条形图和箱线图:
我需要将它们组合成一个图形。我该怎么做?
我尝试在箱形图命令行中使用 add = TRUE
,但它们不合适。
这是一个使用 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()
在基地 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),