如何筛选Zone列为M的行使用ggplot2绘制探索性散点图
你可以通过两种方式实现仅绘制Zone为"M"的记录:
方法1:绘图时直接过滤数据集
无需提前修改原数据集,直接在ggplot的data参数中筛选符合条件的行即可,基础R语法写法如下:
library(ggplot2) # Distance随时间变化图 ggplot(datmarsh[datmarsh$Zone == "M", ], aes(x=Year, y=Distance)) + geom_point() # Distance与MHT的关系图 ggplot(datmarsh[datmarsh$Zone == "M", ], aes(x=MHT, y=Distance)) + geom_point()
如果你习惯使用dplyr语法,也可以用filter函数筛选:
library(ggplot2) library(dplyr) ggplot(datmarsh %>% filter(Zone == "M"), aes(x=Year, y=Distance)) + geom_point() ggplot(datmarsh %>% filter(Zone == "M"), aes(x=MHT, y=Distance)) + geom_point()
方法2:提前创建Zone=M的子集
如果后续还要多次用到M区域的分析数据,可以先单独提取子集备用:
# 提取仅Zone为"M"的数据集 dat_m <- datmarsh[datmarsh$Zone == "M", ] # 若用dplyr写法为:dat_m <- datmarsh %>% filter(Zone == "M") # 绘图直接调用子集即可 ggplot(dat_m, aes(x=Year, y=Distance)) + geom_point() ggplot(dat_m, aes(x=MHT, y=Distance)) + geom_point()
内容的提问来源于stack exchange,提问作者Alison Meeth
相关产品推荐
相关产品推荐

