首页 > 解决方案 > 如何仅在 R 中的阴影状态上编写状态缩写

问题描述

下面是我的代码的一部分,它给出了情节:(阴影状态是紫色的)

在此处输入图像描述

 dt <- statepop %>%
    dplyr::mutate(selected = factor(ifelse(full %in% stringr::str_pad(c(s.cls.list[[i]]$State), 5, pad = "0"), "1", "0")))
  
  s.plot <- usmap::plot_usmap(data = dt, values = "selected", color = "grey") +
    ggplot2::scale_fill_manual(values = c("#E5E4E2", "purple"),name = length(c(s.cls.list[[i]]$State)))+
    labs(title = paste("component",i, sep = " : "))+
    theme(plot.title = element_text(color = "purple", size = 14, face = "bold",hjust = 0.5))+
    

我想要进行两项修改,但我不知道该怎么做:
1- 如何在中心写阴影状态缩写,字体颜色为黄色。
2-我怎样才能拥有这样的情节标题:组件:为黑色,11为紫色,如阴影状态。

标签: rggplot2plot

解决方案


  1. 获取所选州的经度和纬度。我用过rnaturalearth,但你可以有其他选择来做到这一点。
  2. 用于usmap_transform将这些值转换为与您的地图一致。
  3. 使用 `geom_text' 添加标签,
  4. 用来annotate代替title。选择这些值需要一些尝试和错误,因为我没有使用usmap包的经验。
library(usmap)
library(tidyverse)
library(rnaturalearth)
select_states <- c("Nebraska", "New Mexico", "Oregon")
dt <- statepop %>%
  dplyr::mutate(selected = ifelse(full %in% select_states, "1", "0"))
s.plot <- usmap::plot_usmap(data = dt, values = "selected", color = "grey") +
  ggplot2::scale_fill_manual(values = c("#E5E4E2", "purple"), 
                             #name = length(c(s.cls.list[[i]]$State))
  )+
  labs(title = paste("component","?", sep = " : "))+
  theme(plot.title = element_text(color = "purple", size = 14, face = "bold",hjust = 0.5))

my_df <-rnaturalearth::ne_states(country = "united states of america") %>% as.data.frame() %>% 
  filter(name %in% select_states) %>% transmute(lon = longitude, lat = latitude, state = name, abbr = postal)%>% 
  usmap_transform()

s.plot +
  geom_text(data = my_df, aes(x = lon.1, y = lat.1, label = abbr)) + 
  labs(title = "") +
  annotate("label", x = 26203.63, y = 874416.52, color = "black", fill = "purple", 
           label = paste("component","?", sep = " : ")) 

reprex 包于 2021-09-02 创建(v2.0.1)


推荐阅读