【问题标题】:Scatter plot with ggplot, using indexing to plot subsets of the same variable on x and y axis带有 ggplot 的散点图,使用索引在 x 和 y 轴上绘制相同变量的子集
【发布时间】:2022-01-07 07:31:04
【问题描述】:

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

使用 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"))

【问题讨论】:

    标签: ggplot2 indexing subset scatter-plot scatter


    【解决方案1】:

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

    使用一些随机的假数据:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 2018-12-19
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多