You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中基于列条件(2017年+wrap作物)绘制散点图

筛选特定条件数据绘制ggplot散点图

问题背景

现有数据框B8A,结构如下:

dput(B8A)
structure(list(ID = c("AUR", "AUR", "AUR", "AUR", "AUR", "AUR", 
"LAM", "LAM", "LAM", "LAM", "LAM", "LAM", "P0", "P01", "P02", 
"P1", "P18", "P2", "P22", "P23", "P24", "P3", "P4"), nD_SOS = c(129L, 
349L, 256L, 319L, 306L, 128L, 309L, 244L, 134L, 356L, 131L, 302L, 
276L, 296L, 294L, 310L, 337L, 291L, 308L, 295L, 308L, 303L, 310L
), nNDVI_SOS = c(119L, 374L, 272L, 329L, 328L, 152L, 317L, 246L, 
129L, 378L, 152L, 315L, 358L, 314L, 310L, 305L, 363L, 305L, 281L, 
274L, 285L, 302L, 311L), crop = c("sunfl", "wwht", "wrap", "wwht", 
"fbn", "sunfl", "wwht", "wmust_vetch", "irr_corn", "wwht", "irr_corn", 
"wwht", "wrap", "wrap", "wrap", "wrap", "wwht", "wrap", "wrap", 
"wrap", "wrap", "wrap", "wrap"), year = c(2016, 2016, 2017, 2018, 
2019, 2020, 2015, 2016, 2017, 2017, 2019, 2019, 2016, 2016, 2016, 
2017, 2018, 2017, 2015, 2015, 2015, 2017, 2018)), row.names = c(NA, 
-23L), class = "data.frame")

需要绘制nD_SOS与nNDVI_SOS的散点图,但仅展示year为2017且crop为wrap的数据,现有ggplot代码如下,需添加筛选逻辑:

p3 <- ggplot(nB8A_SOS_KRR25_crop, aes(x=nNDVI_SOS, y=nD_SOS)) +
  geom_point() +
  stat_regline_equation(label.x=30, label.y=310) +
  stat_cor(aes(label=..rr.label..), label.x=30, label.y=290)+
  geom_smooth(method=lm , color="red", fill="#69b3a2", se=TRUE) +
  ggtitle("B8A KRR 25") +
  theme_ipsum()

p3

解决方案

有两种常用方式实现数据筛选:

方式1:提前筛选数据框(推荐)

使用dplyr::filter或基础R的subset先提取符合条件的数据,再传入ggplot:

# 若使用dplyr
library(dplyr)
filtered_data <- B8A %>% filter(year == 2017, crop == "wrap")

# 若使用基础R
filtered_data <- subset(B8A, year == 2017 & crop == "wrap")

# 绘制图形
p3 <- ggplot(filtered_data, aes(x=nNDVI_SOS, y=nD_SOS)) +
  geom_point() +
  stat_regline_equation(label.x=30, label.y=310) +
  stat_cor(aes(label=..rr.label..), label.x=30, label.y=290)+
  geom_smooth(method=lm , color="red", fill="#69b3a2", se=TRUE) +
  ggtitle("B8A KRR 25 (2017, wrap)") +
  theme_ipsum()

p3

方式2:在ggplot的data参数中直接筛选

无需提前创建新数据框,直接在ggplot调用时指定筛选条件:

p3 <- ggplot(subset(B8A, year == 2017 & crop == "wrap"), aes(x=nNDVI_SOS, y=nD_SOS)) +
  geom_point() +
  stat_regline_equation(label.x=30, label.y=310) +
  stat_cor(aes(label=..rr.label..), label.x=30, label.y=290)+
  geom_smooth(method=lm , color="red", fill="#69b3a2", se=TRUE) +
  ggtitle("B8A KRR 25 (2017, wrap)") +
  theme_ipsum()

p3

两种方式都能精准筛选出year=2017且crop="wrap"的数据,仅展示符合条件的散点及回归分析结果。

内容的提问来源于stack exchange,提问作者Cláudio Siva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 09:35:21