R - 在ggplot2地图

时间:2018-02-22 01:05:34

标签: r ggplot2 maps

我正在尝试使用以下代码绘制美国所有县的渐变填充地图。我想要一个连续的深蓝色 - >地图填充的深色渐变填充,但由于某种原因我的代码没有这样做,即使我添加:

scale_colour_gradientn("Title", colours = c("darkblue", "darkred"),
                        values = c(0,1))

到情节。在这种情况下,如何从深蓝色到暗红色渐变渐变(数据比例从0到1)?

counties_dem_rep <- read.csv("2016_US_County_Level_Presidential_Results.csv", header = TRUE, sep = ",")

library(ggplot2)
library(fiftystater)
library(colorplaner)
library(USAboundaries)
library(sf)
library(dplyr)

usc <- us_counties(resolution = c("low", "high"), states = NULL)

temp_count_NM <- us_counties(states = "New Mexico", resolution ='high')

st_list = c("Alabama", "Arizona", "Arkansas", "California", "Colorado", 
            "Connecticut", "Delaware", "Florida", "Georgia", "Idaho", "Illinois", 
            "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland", 
            "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", 
            "Montana", "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New 
            Mexico", "New York", "North Carolina", "North Dakota", "Ohio", "Oklahoma", 
            "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota", 
            "Tennessee", "Texas", "Utah", "Vermont", "Virginia", "Washington", "West 
            Virginia", "Wisconsin", "Wyoming")

plot_counties <- us_counties(states=st_list, resolution = 'high')
plot_counties$geoid <- as.numeric(plot_counties$geoid)
colnames(counties_dem_rep)[11] <- "geoid"

plot_counties <- inner_join(plot_counties, counties_dem_rep, by = "geoid")

plot_states <- us_states(states=st_list, resolution = 'high')

temp_count_NM$geoid <- as.numeric(temp_count_NM$geoid)

temp_count_NM <- inner_join(temp_count_NM, counties_dem_rep, by = "geoid")



devtools::install_github("tidyverse/ggplot2")
require(ggplot2)

ggplot(plot_counties) + 
  geom_sf(aes(fill=per_gop), color=NA) + 
  geom_sf(data=plot_states, fill=NA, color="black", lwd=0.25) + 
  scale_x_continuous(breaks = NULL) + 
  scale_y_continuous(breaks = NULL) +
  scale_colour_gradientn("Title", colours = c("darkblue", "darkred"),
                        values = c(0,1))+ 
  theme(panel.background = element_blank(), axis.ticks = element_blank(), 
        axis.text = element_blank())

目前我得到以下情节: enter image description here

1 个答案:

答案 0 :(得分:2)

您已在此行fill中将color设置为值,并将geom_sf(aes(fill=per_gop), color=NA)设置为NA。我怀疑这意味着您应该使用scale_fill_gradientn而不是scale_color_gradientn