英文:
How to make a scatterplot with grouping variables?
问题
以下是翻译好的部分:
"假设我有一个数据集,看起来像图片中显示的样子,并且我想制作一个散点图,其中x轴表示A测试阶段的结果,y轴表示B测试阶段的结果。结果是一个连续变量。图中应该有四个数据点,分别代表四个主题。我应该如何在R中使用ggplot来实现呢?
ggplot(data, aes(x = results, y = results)) + geom_point()
这是我尝试的,但它没有给我想要的结果。"
英文:
Say I have a dataset that looks like what is shown in the picture, and I want to make a scatterplot whose x-axis presents the results during the A test phase and y-axis presents the results during the B test phase. The results is a continous variable. There should be four data points pinpointed in the graph, representing the four subjects. How am I supposed to do it with ggplot in R?
ggplot(data, aes(x = results, y = results)) + geom_point()
This is what I tried, but it does not give me what I wanted.
答案1
得分: 0
以下是翻译好的部分:
"在这种情况下,您需要将test_phase
数据以宽格式呈现,因为这些值提供了绘图的x、y坐标。这可以通过使用tidyr::pivot_wider
来实现。之后,一切都归结为使用ggplot进行格式化。
# 一些虚拟数据
set.seed(12)
df1 <- data.frame(subject = rep(1:4, 2),
test_phase = rep(c("A", "B"), each = 4),
results = sample(1000:6000, 8))
# 用于数据整理和绘图的包
library(tidyr)
library(ggplot2)
df1 |>
pivot_wider(names_from = test_phase, values_from = results) |>
ggplot(aes(A, B, colour = factor(subject))) +
geom_point() +
labs(colour = "Subject")
<!-- -->
<sup>创建于2023年06月26日,使用reprex v2.0.2</sup>"
英文:
You'll need the test_phase
data in wide format in this case as the values provide the x, y coordinates of the plot. This can be achieved using tidyr::pivot_wider
. After that it all down to formatting with ggplot.
# Some dummy data
set.seed(12)
df1 <- data.frame(subject = rep(1:4, 2),
test_phase = rep(c("A", "B"), each = 4),
results = sample(1000:6000, 8))
# packages for data wrangling and plotting
library(tidyr)
library(ggplot2)
df1 |>
pivot_wider(names_from = test_phase, values_from = results) |>
ggplot(aes(A, B, colour = factor(subject))) +
geom_point() +
labs(colour = "Subject")
<!-- -->
<sup>Created on 2023-06-26 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论