简体   繁体   English

ggplot2 - 来自不同长度的来源的多个箱图

[英]ggplot2 - Multiple Boxplots from Sources of Different Lengths

I have a few different vectors of varying length for which I would like to generate side by side boxplots using ggplot2. 我有一些不同长度的不同载体,我想使用ggplot2生成并排的箱形图。 This is relatively straight forward to do with the Base plotting system. 这与Base绘图系统相对简单。 However ggplot2 only takes a single data frame as input, which is difficult to create from data of varying lengths. 然而,ggplot2仅将单个数据帧作为输入,这很难从不同长度的数据创建。

a <- rnorm(10)
b <- rnorm(100)
c <- rnorm(1000)
boxplot(a, b, c)

Q: What is the correct way to draw boxplots using ggplot2 using data of varying lengths? 问:使用不同长度的数据使用ggplot2绘制箱图的正确方法是什么?


ggplot uses tidy long data frames with groups (like a, b, or c) saved as separate columns. ggplot使用整齐的长数据帧,其中组(如a,b或c)保存为单独的列。 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: 在您的示例中,您可以创建一个包含1110行(10 + 100 + 1000)和两列(值和组)的数据框,如下所示:

# 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()

示例boxplot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM