R语言 使用ggplot在连续栅格上绘制离散比例

dtcbnfnu  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(160)

如问题所述,我想在光栅高程图(连续比例)上绘制由因子(离散)着色的数据。我尝试单独指定比例(使用scale_fill_gradientn()scale_color_manual()),但错误仍然存在。
有没有办法做到这一点,或者我只需要放弃高程光栅?
下面是一个可重复的示例:

library(spData)
library(elevatr)
library(dplyr)

california <- us_states %>%
  filter(NAME == "California")

# Import elevation data
ca.elevations <- get_elev_raster(locations = california, z = 5, clip = "locations")

# Convert elevation raster to df, keeping only elevation, not bathymetry
ca.elevation.df <- raster::as.data.frame(ca.elevations, xy = TRUE) %>%
  rename(elevation =  3) %>%
  na.omit() %>%
  filter(elevation >= 0)

background.map <- ggplot()+
  geom_tile(data = ca.elevation.df, aes(x = x, y = y, fill = elevation))+
  scale_fill_gradientn(colours= c("gray90", "black"), values= scales::rescale(c(0, 300, 900, 1000, 1900, 2000, 3900, 4000, 10000)), guide = "none")+
  geom_sf(data = california, fill = NA)

# Add discrete data to map
pie.data <- data.frame(pie = c("a","b", "c"), part.1 = rep(0.5, 3), part.2 = rep(0.5, 3),
                       lat = c(34,36,38), long = c(122,120,118))

# Works
ggplot()+
  geom_scatterpie(data = pie.data, 
                  aes(x = long, y = lat, group = pie),
                  cols = c("part.1", "part.2"))
# Doesn't work
background.map+
  geom_scatterpie(data = pie.data, 
                  aes(x = long, y = lat, group = pie),
                  cols = c("part.1", "part.2"))
9w11ddsr

9w11ddsr1#

一种管理方法是使用ggnewscale添加新的比例。请注意,我修改了您的数据,使pie.data数据框中的所有经度为负。

library(spData)
library(elevatr)
library(dplyr)
library(scatterpie)

california <- us_states %>%
  filter(NAME == "California")

# Import elevation data
ca.elevations <- get_elev_raster(locations = california, z = 5, clip = "locations")
#> Mosaicing & Projecting
#> Clipping DEM to locations
#> Note: Elevation units are in meters.

# Convert elevation raster to df, keeping only elevation, not bathymetry
ca.elevation.df <- raster::as.data.frame(ca.elevations, xy = TRUE) %>%
  rename(elevation =  3) %>%
  na.omit() %>%
  filter(elevation >= 0)

background.map <- ggplot()+
  geom_tile(data = ca.elevation.df, aes(x = x, y = y, fill = elevation))+
  scale_fill_gradientn(colours= c("gray90", "black"), values= scales::rescale(c(0, 300, 900, 1000, 1900, 2000, 3900, 4000, 10000)), guide = "none")+
  geom_sf(data = california, fill = NA)

# Add discrete data to map
pie.data <- data.frame(pie = c("a","b", "c"), part.1 = rep(0.5, 3), part.2 = rep(0.5, 3),
                       lat = c(34,36,38), long = c(-122,-120,-118))

# Works now
background.map+
  ggnewscale::new_scale_fill() +
  geom_scatterpie(data = pie.data, 
                  aes(x = long, y = lat, group = pie),
                  cols = c("part.1", "part.2"))

创建于2023-04-07带有reprex v2.0.2

相关问题