ggmap:在应用渐变比例后将特定颜色应用于值 [英] ggmap: apply specific color to value after applying gradient scale

查看:70
本文介绍了ggmap:在应用渐变比例后将特定颜色应用于值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用渐变来填充地图上的颜色,但是我需要特定的值(例如零)才能成为特定的颜色(例如红色或灰色).

有什么方法可以首先应用渐变,然后设置这些特定的颜色值?如果可能的话,我希望能够针对多个特定值进行操作.

在下面的示例中,如何将0值设为红色?

  suppressPackageStartupMessages(require(tidyverse))preventPackageStartupMessages(require(ggmap))preventPackageStartupMessages(require(viridis))preventPackageStartupMessages(require(albersusa))#devtools :: install_github("hrbrmstr/albersusa")我们<-usa_composite()us_map<-强化(us,region ="name")%>%重命名(状态= ID)dat<-tibble(状态= state.name,值=样本(-2:5,50,替换= T))dat%&%;%right_join(us_map)%>%ggplot()+geom_polygon(aes(x = long,y = lat,fill = value,group = group),color ="white",size = .2)+coord_fixed(1.3)+scale_fill_viridis()#>通过="state"加入 

I'd like to be able to use a gradient to fill the colors on a map, but I need specific values (like zero) to be a specific color (say, red or grey).

Is there some way to first apply the gradient, and then set these specific color values? I'd like to be able to do it for multiple specific values if possible.

In the example below, how could we make the 0 values red?

suppressPackageStartupMessages(require(tidyverse))
suppressPackageStartupMessages(require(ggmap))
suppressPackageStartupMessages(require(viridis))
suppressPackageStartupMessages(require(albersusa)) #devtools::install_github("hrbrmstr/albersusa")

us <- usa_composite()
us_map <- fortify(us, region="name") %>% 
  rename(state = id)


dat <- tibble(state = state.name, value = sample(-2:5, 50, replace = T))

dat %>% 
  right_join(us_map) %>% 
  ggplot() +
  geom_polygon(aes(x = long, y = lat, fill = value, group = group), color = "white", size = .2) +
  coord_fixed(1.3) +
  scale_fill_viridis()
#> Joining, by = "state"

Created on 2019-02-20 by the reprex package (v0.2.1)

解决方案

You can change 0 to NA in your plot data object and within scale_fill_viridis use argument na.value:

# Create plot data object
pd <- right_join(dat, us_map)
# Replace wanted value with NA
pd$value[pd$value == 0] <- NA

ggplot(pd, aes(long, lat, fill = value, group = group)) +
    geom_polygon(color = "white", size = 0.2) +
    coord_fixed(1.3) +
    scale_fill_viridis(na.value = "red")

这篇关于ggmap:在应用渐变比例后将特定颜色应用于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆