使用 ggplot 绘制散点图,使用索引在 x 和 y 轴上绘制相同变量的子集

Scatter plot with ggplot, using indexing to plot subsets of the same variable on x and y axis

我正在处理希思罗机场下载的英国气象局数据的一部分天气数据。此数据集不包含缺失值。

我想使用 ggplot 创建希思罗机场最高温度 (tmax) 的散点图,并将 2018 年的数据与 2019 年的数据进行对比(见下文示例)。 2018年和2019年都有12个数据点。

我已经在下面尝试过,但是它不起作用。这似乎是由于索引,因为当不尝试在 aes() 函数中使用索引时代码工作正常。

我怎样才能让它工作?

2018Index <- which(HeathrowData$Year == 2018) 
2019Index <- which(HeathrowData$Year == 2019) 

scatter<-ggplot(HeathrowData, aes(tmax[2018Index], tmax[2019Index]))
scatter + geom_point()
scatter + geom_point(size = 2) + labs(x = "2018", y = "2019"))

由于您的数据是长格式的,您需要进行一些数据整理,以便将您的年份值放在单独的列中,也就是您必须将数据重塑为宽格式:

使用一些随机的假数据:

library(dplyr)
library(tidyr)
library(ggplot2)

# Example data
set.seed(123)

HeathrowData <- data.frame(
  Year = rep(2017:2019, each = 12),
  tmax = runif(36)
)

# Select, Filter, Convert to Wide
HeathrowData <- HeathrowData %>% 
  select(Year, tmax) %>% 
  filter(Year %in% c(2018, 2019)) %>% 
  group_by(Year) %>% 
  mutate(id = row_number()) %>% 
  ungroup() %>% 
  pivot_wider(names_from = Year, values_from = tmax, names_prefix = "y")

ggplot(HeathrowData, aes(y2018, y2019)) +
  geom_point(size = 2) +
  labs(x = "2018", y = "2019")