[英]Filter and exclude a level in stat_density2d_filled
I have code and data like that to map some locations in the USA:我有类似 map 美国某些地点的代码和数据:
library(sf)
library(tidyverse)
set.seed(123) # for reproducibility
Latitude = round(runif(5000, 31, 46), digits = 5)
Longitude = round(runif(5000, -120, -80), digits = 5)
df = data.frame(Latitude, Longitude)
world <- ne_countries(scale = "medium", returnclass = "sf")
usa = filter(world,admin =="United States of America")
# Plot
ggplot() +
geom_sf(data = usa, fill = "blue",color = "black",alpha=.9) +
coord_sf(
xlim = c(-119, -74),
ylim = c(22, 51),
default_crs = sf::st_crs(4326),
crs = st_crs("ESRI:102003"),
expand = TRUE,
lims_method = "box",
label_axes = list(
bottom = "E", top = "E",
left = "N", right = "N"
))+stat_density2d_filled(data = df, aes(x = Longitude, y = Latitude, fill=(..level..),
alpha = (..level..)), geom = "polygon")
I have the output like this:我有这样的 output:
I am looking to exclude some levels like (0,0002,0004], and (0,0004,0006]. Additionally, I would like to manually color the levels. I have this code scale_fill_manual(values = c("khaki1", "khaki2", "khaki2", "orange", "orange", "red", "red", "red", "red"))
, however would like to use scale_fill_gradientn
and color palettes in the RColorBrewer package like YlOrRd.我希望排除一些级别,例如 (0,0002,0004] 和 (0,0004,0006)。此外,我想手动为级别着色。我有此代码
scale_fill_manual(values = c("khaki1", "khaki2", "khaki2", "orange", "orange", "red", "red", "red", "red"))
,但是想在 RColorBrewer package 中使用scale_fill_gradientn
和调色板,如 YlOrRd。
I don't have the usa basemap layer, but does this do what you want with your density layer?我没有美国底图图层,但是这对你的密度图层有什么作用吗?
library(sf)
#> Linking to GEOS 3.10.2, GDAL 3.4.2, PROJ 8.2.1; sf_use_s2() is TRUE
library(ggplot2)
library(tidyverse)
set.seed(123) # for reproducibility
Latitude = round(runif(5000, 31, 46), digits = 5)
Longitude = round(runif(5000, -120, -80), digits = 5)
df = data.frame(Latitude, Longitude)
breaks <- seq(from = 0.0006, to = 0.0020, by = 0.0002)
# Plot
ggplot() +
# geom_sf(data = usa, fill = "blue",color = "black",alpha=.9) +
coord_sf(
xlim = c(-119, -74),
ylim = c(22, 51),
default_crs = sf::st_crs(4326),
crs = st_crs("ESRI:102003"),
expand = TRUE,
lims_method = "box",
label_axes = list(
bottom = "E", top = "E",
left = "N", right = "N"
)) +
stat_density2d_filled(data = df,
aes(x = Longitude, y = Latitude,
fill = after_stat(level),
alpha = after_stat(level)),
geom = "polygon",
breaks = breaks) +
scale_fill_brewer(palette = "YlOrRd")
Created on 2023-01-31 by the reprex package (v2.0.1)由reprex package (v2.0.1) 创建于 2023-01-31
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.