R语言 过滤并排除stat_density2d_filled中的水平

hc2pp10m  于 2023-02-01  发布在  其他
关注(0)|答案(1)|浏览(102)

我有这样的代码和数据来绘制美国的一些位置:

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")

输出如下:

我希望排除一些水平,如(0,0002,0004],和(0,0004,0006]。此外,我想手动着色的水平。我有这个代码scale_fill_manual(values = c("khaki1", "khaki2", "khaki2", "orange", "orange", "red", "red", "red", "red")),但想使用scale_fill_gradientn和调色板的RColorBrewer包,如YlOrRd。

qhhrdooz

qhhrdooz1#

我没有美国底图图层,但这是否做你想与你的密度层?

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")

reprex package(v2.0.1)于2023年1月31日创建

相关问题