如何在stat_density2d_filled中排除指定层级并自定义颜色?
解决方案
以下是修改后的R代码,实现了排除指定密度层级并改用scale_fill_gradientn结合YlOrRd调色板的需求:
# 加载依赖包 library(ggplot2) library(RColorBrewer) library(maps) # 获取美国州界地图数据 usa_states <- map_data("state") # 假设你的位置数据存储在location_df中,包含lon(经度)、lat(纬度)列 # 绘制密度图并调整层级与填充方式 ggplot(location_df, aes(x = lon, y = lat)) + # 绘制美国地图底图 geom_polygon(data = usa_states, aes(x = long, y = lat, group = group), fill = "white", color = "gray50") + # 生成密度多边形,通过breaks跳过不需要的层级 stat_density2d(aes(fill = after_stat(density)), geom = "polygon", breaks = c(0, 0.0002, 0.0006, 0.0008, 0.001, 0.0012)) + # 使用YlOrRd调色板的渐变填充 scale_fill_gradientn( colours = brewer.pal(n = 5, "YlOrRd"), name = "Density", breaks = c(0.0002, 0.0006, 0.0008, 0.001, 0.0012), labels = c("0–0.0002", ">0.0006–0.0008", ">0.0008–0.001", ">0.001–0.0012") ) + # 应用地图投影坐标 coord_map() + theme_minimal()
关键修改说明
排除指定层级
- 如果是通过
stat_density2d自动生成密度层级:直接调整breaks参数,跳过0.0002到0.0006之间的两个区间(即不生成(0.0002, 0.0004]和(0.0004, 0.0006]的多边形)。 - 如果是预先对密度值分好组:通过数据过滤移除不需要的层级,示例代码如下:
# 假设数据框中有density_group列,存储分组标签 filtered_df <- location_df[!location_df$density_group %in% c("(0.0002,0.0004]","(0.0004,0.0006]"), ]
- 如果是通过
替换填充方式
- 移除原有的
scale_fill_manual,改用scale_fill_gradientn实现渐变填充。 - 用
brewer.pal(n = 5, "YlOrRd")调用RColorBrewer包的YlOrRd调色板,n值需与你保留的层级数量匹配。 - 调整
breaks和labels参数,确保图例与过滤后的密度层级对应。
- 移除原有的
内容的提问来源于stack exchange,提问作者Ali Roghani
相关产品推荐
相关产品推荐

