在 ggplot2 上为不同长度的向量创建小提琴图?
Creating violin plots on ggplot2 for vectors of different length?
我有两个不同长度的向量,想为它们创建一个小提琴图。我目前正在做的是 cbind
它们,这使得较短的向量被重复,直到它匹配较长向量的长度(默认情况下由 R 中的 cbind
完成)。
library(ggplot2)
C1 <- rnorm(100)
C2 <- rnorm(500)
dat <- cbind(C1,C2)
# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)
pp <- ggplot(mat, aes(x = variable, y = value)) + geom_violin(scale="width",adjust = 1,width = 0.5,fill = "gray80")
pp
这会影响小提琴的形状吗?有没有更正确的方法来创建小提琴情节而不必人为地增加其中一个情节的长度?
与其 cbind
使用两个不同长度的向量,这会导致循环,然后熔化,不如制作两个数据框,在其中标记每个代表的内容并 rbind
它们。这样一来,您就可以从 ggplot
预期形状的数据开始,并且不会 运行 重复两组数据中较短数据的值的风险。
library(ggplot2)
set.seed(710)
C1 <- data.frame(value = rnorm(100), variable = "C1")
C2 <- data.frame(value = rnorm(500), variable = "C2")
dat <- rbind(C1, C2)
head(dat)
#> value variable
#> 1 -0.97642446 C1
#> 2 -0.51938107 C1
#> 3 1.05793223 C1
#> 4 -0.88139935 C1
#> 5 -0.05997154 C1
#> 6 0.31960235 C1
ggplot(dat, aes(x = variable, y = value)) +
geom_violin(scale = "width", adjust = 1, width = 0.5)
由 reprex package (v0.2.0) 创建于 2018-07-11。
我有两个不同长度的向量,想为它们创建一个小提琴图。我目前正在做的是 cbind
它们,这使得较短的向量被重复,直到它匹配较长向量的长度(默认情况下由 R 中的 cbind
完成)。
library(ggplot2)
C1 <- rnorm(100)
C2 <- rnorm(500)
dat <- cbind(C1,C2)
# Violin plots for columns
mat <- reshape2::melt(data.frame(dat), id.vars = NULL)
pp <- ggplot(mat, aes(x = variable, y = value)) + geom_violin(scale="width",adjust = 1,width = 0.5,fill = "gray80")
pp
这会影响小提琴的形状吗?有没有更正确的方法来创建小提琴情节而不必人为地增加其中一个情节的长度?
与其 cbind
使用两个不同长度的向量,这会导致循环,然后熔化,不如制作两个数据框,在其中标记每个代表的内容并 rbind
它们。这样一来,您就可以从 ggplot
预期形状的数据开始,并且不会 运行 重复两组数据中较短数据的值的风险。
library(ggplot2)
set.seed(710)
C1 <- data.frame(value = rnorm(100), variable = "C1")
C2 <- data.frame(value = rnorm(500), variable = "C2")
dat <- rbind(C1, C2)
head(dat)
#> value variable
#> 1 -0.97642446 C1
#> 2 -0.51938107 C1
#> 3 1.05793223 C1
#> 4 -0.88139935 C1
#> 5 -0.05997154 C1
#> 6 0.31960235 C1
ggplot(dat, aes(x = variable, y = value)) +
geom_violin(scale = "width", adjust = 1, width = 0.5)
由 reprex package (v0.2.0) 创建于 2018-07-11。