如何制作具有分组变量的散点图?

huangapple go评论71阅读模式
英文:

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 |&gt; 
  pivot_wider(names_from = test_phase, values_from = results) |&gt; 
  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 &lt;- data.frame(subject = rep(1:4, 2),
                  test_phase = rep(c(&quot;A&quot;, &quot;B&quot;), each = 4),
                  results = sample(1000:6000, 8))

# packages for data wrangling and plotting
library(tidyr)
library(ggplot2)

df1 |&gt; 
  pivot_wider(names_from = test_phase, values_from = results) |&gt; 
  ggplot(aes(A, B, colour = factor(subject))) +
  geom_point() +
  labs(colour = &quot;Subject&quot;)

如何制作具有分组变量的散点图?<!-- -->

<sup>Created on 2023-06-26 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年6月26日 15:53:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76554617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定