在地理空间中结合分类填充和渐变填充-R [英] Combine Categorical and Gradient Fill in Geospatial - R
问题描述
我正在尝试在地图上填充组合的分类变量和连续变量.因此,举例来说,在下面的示例中,我想显示每个县的KrispyKreme Donut商店数量,通常这是我想在渐变上填充的连续变量.但是我也有一些县禁止用"-1"表示的KrispyKremes县和那些正在建设中的"-2"的县.我想以未映射在渐变上的其他颜色显示这些.我的真实数据中也没有NA.
I'm trying to fill a combined categorical and continuous variable on a map. So, for instance, in my minimally reproducible example below, say I want to display the number of KrispyKreme Donut shops in each county, which is generally a continuous variable I want to fill on a gradient. But I also have counties that forbid KrispyKremes indicated by a "-1" and those that have them under construction "-2". I want to display these in a different color not mapped on the gradient. I also have NA in my real data.
-到目前为止,我所拥有的:
--What I have so far:
library(sf)
library(ggplot2)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc$Status<-rep(c(-2,-1,runif(8)), 10)
ggplot(nc) +
geom_sf(aes(fill=Status),color = "black") +
coord_sf(datum = NA) +
theme_minimal()
如果我添加以下行,显然会中断.所以,我知道我的语法有误,但这表明我想尽最大努力做到这一点
It breaks if I add the following line, obviously. So, I know I have the syntax wrong but it indicates what I want to do in as best as I can figure code for this
scale_fill_manual(breaks= c("-2","-1", >=0),values = c("blue", "yellow", scale_fill_viridis()))
非常感谢您的帮助,我整天都在工作.
Any help is much appreciated, I've been on this all day.
推荐答案
您将需要将连续变量切成不同的类别.
You will need to cut your continuous variable into different categories.
library(sf)
library(ggplot2)
library(dplyr)
# Set seed for reproducibility
set.seed(122)
nc <- st_read(system.file("shape/nc.shp", package="sf"))
nc$Status<-rep(c(-2,-1,runif(8)), 10)
首先,检查变量的分布.
First, check the distribution of your variable.
nc %>%
filter(Status >= 0) %>%
pull("Status") %>%
summary()
# Min. 1st Qu. Median Mean 3rd Qu. Max.
# 0.002789 0.153144 0.602395 0.491287 0.735787 0.906851
我决定根据分位数如下切割变量.
I decided to cut the variable based on the quantile as follows.
nc2 <- nc %>%
mutate(Status2 = case_when(
Status == -2 ~ "-2",
Status == -1 ~ "-1",
Status >= 0 & Status < 0.15 ~ "0 - 0.15",
Status >= 0.15 & Status < 0.6 ~ "0.15 - 0.6",
Status >= 0.6 & Status < 0.75 ~ "0.6 - 0.75",
Status >= 0.75 ~ "0.75 - 0.91"
))
现在, Status2
是一个分类变量.我们可以绘制它并使用 scale_fill_manual
提供颜色.注意,我们需要在 values
参数中提供颜色代码. viridis :: viridis(4)
用于基于绿色元素生成四种颜色.
Now Status2
is a categorical variable. We can plot it and use scale_fill_manual
to provide colors. Notice that we need to provide the color code in the values
argument. viridis::viridis(4)
is to generate four colors based on the viridis.
ggplot(nc2) +
geom_sf(aes(fill=Status2),color = "black") +
coord_sf(datum = NA) +
theme_minimal() +
scale_fill_manual(values = c("blue", "yellow", viridis::viridis(4)))
这篇关于在地理空间中结合分类填充和渐变填充-R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!