ggplot2-来自不同长度的来源的多个箱形图 [英] ggplot2 - Multiple Boxplots from Sources of Different Lengths
问题描述
我有一些不同长度的不同向量,我想使用ggplot2并排生成箱形图.这与基本绘图系统比较直接.但是,ggplot2仅将单个数据帧作为输入,这很难根据长度不同的数据来创建.
I have a few different vectors of varying length for which I would like to generate side by side boxplots using ggplot2. This is relatively straight forward to do with the Base plotting system. However ggplot2 only takes a single data frame as input, which is difficult to create from data of varying lengths.
a <- rnorm(10)
b <- rnorm(100)
c <- rnorm(1000)
boxplot(a, b, c)
问:使用ggplot2使用不同长度的数据绘制箱形图的正确方法是什么?
Q: What is the correct way to draw boxplots using ggplot2 using data of varying lengths?
推荐答案
ggplot使用整齐的长数据帧,并将组(如a,b或c)保存为单独的列.在您的示例中,您可以创建一个包含1110行(10 + 100 + 1000)和两列(值和组)的数据框,如下所示:
ggplot uses tidy long data frames with groups (like a, b, or c) saved as separate columns. In your example, you can make a data frame with 1110 rows (10 + 100 + 1000) and two columns (the value and the group), like so:
# Make individual data frames
a <- data.frame(group = "a", value = rnorm(10))
b <- data.frame(group = "b", value = rnorm(100))
c <- data.frame(group = "c", value = rnorm(1000))
# Combine into one long data frame
plot.data <- rbind(a, b, c)
# group value
# 1 a 0.2322682
# 2 a -0.9681992
# ...
# 101 b 0.3422354
# 102 b 0.3495342
# ...
# 1001 c -0.6839231
# 1002 c -1.4329843
# Plot
library(ggplot2)
ggplot(plot.data, aes(x=group, y=value, fill=group)) + geom_boxplot()
这篇关于ggplot2-来自不同长度的来源的多个箱形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!