如何在R中的同一图表中放置多个箱图?

时间:2022-02-17 13:01:57

Sorry I don't have example code for this question.

对不起,我没有这个问题的示例代码。

All I want to know is if it is possible to create multiple side-by-side boxplots in R representing different columns/variables within my data frame. Each boxplot would also only represent a single variable--I would like to set the y-scale to a range of (0,6).

我想知道的是,是否可以在R中创建多个并排的箱图,表示我的数据框中的不同列/变量。每个箱图也只代表一个变量 - 我想将y标度设置为(0,6)的范围。

If this isn't possible, how can I use something like the panel option in ggplot2 if I only want to create a boxplot using a single variable? Thanks!

如果这是不可能的,如果我只想使用单个变量创建一个boxplot,如何使用ggplot2中的panel选项?谢谢!

Ideally, I want something like the image below but without factor grouping like in ggplot2. Again, each boxplot would represent completely separate and single columns.

理想情况下,我想要像下面的图像,但没有像ggplot2那样的因子分组。同样,每个箱图将代表完全独立的单列。

如何在R中的同一图表中放置多个箱图?

2 个解决方案

#1


5  

ggplot2 requires that your data to be plotted on the y-axis are all in one column.

ggplot2要求您在y轴上绘制的数据都在一列中。

Here is an example:

这是一个例子:

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)

如何在R中的同一图表中放置多个箱图?

The ylim(0,6) sets the y-axis to be between 0 and 6

ylim(0,6)将y轴设置在0和6之间

If your data are in columns, you can get them into the longform using melt from reshape2 or gather from tidyr. (other methods also available).

如果您的数据是在列中,您可以使用reshape2中的melt或从tidyr收集来将它们放入longform中。 (也可提供其他方法)。

#2


5  

You can do this if you reshape your data into long format

如果将数据重新整形为长格式,则可以执行此操作

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

如何在R中的同一图表中放置多个箱图?

#1


5  

ggplot2 requires that your data to be plotted on the y-axis are all in one column.

ggplot2要求您在y轴上绘制的数据都在一列中。

Here is an example:

这是一个例子:

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)

如何在R中的同一图表中放置多个箱图?

The ylim(0,6) sets the y-axis to be between 0 and 6

ylim(0,6)将y轴设置在0和6之间

If your data are in columns, you can get them into the longform using melt from reshape2 or gather from tidyr. (other methods also available).

如果您的数据是在列中,您可以使用reshape2中的melt或从tidyr收集来将它们放入longform中。 (也可提供其他方法)。

#2


5  

You can do this if you reshape your data into long format

如果将数据重新整形为长格式,则可以执行此操作

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

如何在R中的同一图表中放置多个箱图?