【问题标题】:How to clip an interpolated layer in R so it does not extend past data boundaries如何在 R 中裁剪一个插值层,使其不会超出数据边界
【发布时间】:2019-01-11 15:00:42
【问题描述】:

我正在尝试使用等值线显示泻湖环境中的电导率横截面。我已将interp()stat_contour() 应用于我的数据,但我想剪切内插输出,使其不会超出我的数据点。这样,横断面中泻湖的水深就很清楚了。这是我目前使用的代码:

cond_df <- read_csv("salinity_profile.csv")

di <- interp(cond_df$stop, cond_df$depth, cond_df$conductivity, 
         xo = seq(min(cond_df$stop), max(cond_df$stop), length = 200), 
         yo = seq(min(cond_df$depth), max(cond_df$depth), length = 200))
dat_interp <- data.frame(expand.grid(x=di$x, y=di$y), z=c(di$z))

ggplot(dat_interp) +
  aes(x=x, y=y, z=z, fill=z)+
  scale_y_reverse() +
  geom_tile()+
  stat_contour(colour="white", size=0.25) +
  scale_fill_viridis_c() +
  theme_tufte(base_family="Helvetica")

这是输出:

interpolated plot

为了帮助澄清,这里是geom_point() 图表的数据,我不希望插值层越过图表的较低点:

cond_df%>%
  ggplot(mapping=aes(x=stop, y=depth, z=conductivity, fill=conductivity)) +
  geom_point(aes(colour = conductivity), size = 3) +
  scale_y_reverse()

point plot

【问题讨论】:

标签: r ggplot2 interpolation contour clip


【解决方案1】:

您可以使用geom_ribbon 屏蔽不需要的绘图区域。

您需要生成一个data.frame,其中包含每个停靠点的最大深度值。这是一种不太优雅的方法:

# Create the empty data frame for all stops 
bathymetry <- data.frame(depth = as.numeric(NA),
                         stop = unique(cond_df$stop))

# Find the max depth for each stop
for(thisStop in bathymetry$stop){
    bathymetry[bathymetry$stop==thisStop, "depth"] <- max(cond_df[cond_df$stop==thisStop, "depth"])
}

然后,您可以将geom_ribbon 添加为情节的最后一个geom,就像这样

geom_ribbon(data=bathymetry, aes(x=stop, ymin=depth, ymax=max(cond_df$depth)), inherit.aes = FALSE)

【讨论】:

    猜你喜欢
    • 2019-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-19
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多