简体   繁体   English

尝试使用 ggplot2 在同一图表上制作 2 个箱线图

[英]Trying to make 2 boxplots on the same graph using ggplot2

I am trying to complete an assignment using some fake data.我正在尝试使用一些虚假数据完成作业。 One thing they would like us to do is make graphs.他们希望我们做的一件事是制作图表。

The data is time for students n=150 to complete a task pre and post an intervention.数据是学生n=150在干预前后完成任务的时间。

I have been able to make graphs like this我已经能够制作这样的图表

Boxplot1 <- ggplot(data, aes(Timepre))
Boxplot1 <- Boxplot1 + geom_boxplot()
Boxplot1
Boxplot2 <- ggplot(data, aes(Timepost))
Boxplot2 <- Boxplot2 + geom_boxplot()
Boxplot2

But I would like both to be on the same graph但我希望两者都在同一张图上

How can I combine these please?请问我该如何结合这些?

From your example I gather you have your data as two vectors with values.从您的示例中,我收集到您的数据作为两个带有值的向量。 The most difficult part about this question is probably getting the data in the right shape.关于这个问题最困难的部分可能是让数据处于正确的形状。

Below, I'll make two vectors of length 150 with some random values.下面,我将使用一些随机值制作两个长度为 150 的向量。

library(ggplot2)

Timepre <- rpois(150, 30)
Timepost <- rpois(150, 20)

ggplot likes to work nicely with data that is in the so called 'long' format, meaning that every observation gets a row of its own in a data.frame . ggplot 喜欢很好地处理所谓的“长”格式的数据,这意味着每个观察在data.frame中都有自己的一行。 We'd need an extra variable, which we'll call x , to keep track of the groups.我们需要一个额外的变量,我们称之为x ,来跟踪组。

df <- data.frame(
  x = rep(c("Pre", "Post"), c(length(Timepre), length(Timepost))),
  y = c(Timepre, Timepost)
)

# You might want to encode the groups as factors with levels in sensible orders
df$x <- factor(df$x, levels = c("Pre", "Post"))

After reshaping the data, plotting is not so difficult and you can probably find hundreds of posts on this site that can show you how to do it.重塑数据后,绘图就没有那么困难了,您可能会在此站点上找到数百篇可以向您展示如何绘制的帖子。

ggplot(df, aes(x, y)) +
  geom_boxplot()

Created on 2021-01-31 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2021 年 1 月 31 日创建

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

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