如何将多个箱线图放在 R 中的同一个图中?
How do I put multiple boxplots in the same graph in R?
抱歉,我没有这个问题的示例代码。
我只想知道是否可以在 R 中创建多个并排的箱线图,代表我的数据框中的不同 columns/variables。每个箱线图也只代表一个变量——我想将 y 尺度设置为 (0,6) 的范围。
如果这不可能,如果我只想使用单个变量创建箱线图,我该如何使用 ggplot2 中的面板选项之类的东西?谢谢!
理想情况下,我想要像下图这样的东西,但没有像 ggplot2 中那样的因子分组。同样,每个箱线图将代表完全独立的单列。
如果您reshape将数据转换为长格式
,则可以执行此操作
## Some sample data
dat <- data.frame(a=rnorm(100), b=rnorm(100), c=rnorm(100))
## Reshape data wide -> long
library(reshape2)
long <- melt(dat)
plot(value ~ variable, data=long)
ggplot2
要求您绘制在 y 轴上的数据都在一列中。
这是一个例子:
set.seed(1)
df <- data.frame(
value = runif(810,0,6),
group = 1:9
)
df
library(ggplot2)
ggplot(df, aes(factor(group), value)) + geom_boxplot() + coord_cartesian(ylim = c(0,6)
ylim(0,6)
设置y轴在0到6之间
如果您的数据在列中,您可以使用 reshape2
中的 melt
或 tidyr
中的 gather
将它们放入长格式中。 (也可以使用其他方法)。
抱歉,我没有这个问题的示例代码。
我只想知道是否可以在 R 中创建多个并排的箱线图,代表我的数据框中的不同 columns/variables。每个箱线图也只代表一个变量——我想将 y 尺度设置为 (0,6) 的范围。
如果这不可能,如果我只想使用单个变量创建箱线图,我该如何使用 ggplot2 中的面板选项之类的东西?谢谢!
理想情况下,我想要像下图这样的东西,但没有像 ggplot2 中那样的因子分组。同样,每个箱线图将代表完全独立的单列。
如果您reshape将数据转换为长格式
,则可以执行此操作## Some sample data
dat <- data.frame(a=rnorm(100), b=rnorm(100), c=rnorm(100))
## Reshape data wide -> long
library(reshape2)
long <- melt(dat)
plot(value ~ variable, data=long)
ggplot2
要求您绘制在 y 轴上的数据都在一列中。
这是一个例子:
set.seed(1)
df <- data.frame(
value = runif(810,0,6),
group = 1:9
)
df
library(ggplot2)
ggplot(df, aes(factor(group), value)) + geom_boxplot() + coord_cartesian(ylim = c(0,6)
ylim(0,6)
设置y轴在0到6之间
如果您的数据在列中,您可以使用 reshape2
中的 melt
或 tidyr
中的 gather
将它们放入长格式中。 (也可以使用其他方法)。