R code to Generating map of US states with specific colors

后端 未结 2 765
夕颜
夕颜 2021-01-26 19:04

I am trying to generate the map of U.S. in which each state can have one of the following colors:

EScolors <- c(\"#7aad42\",\"#4a77bb\",\"#f7931e\",\"#d3dfbd\         


        
相关标签:
2条回答
  • 2021-01-26 19:41

    Using the base maps package can be a little tricky. The order and the naming of the states is not standard, several states have more than one region, i.e. Manhattan island in New York. A little manipulation is required to properly label/color the map.
    In this solution, I created a dataframe statelist to hold the state names, islands and an index. Then merge this with your dataframe, state_info, and then plotted.

    #function to split strings an return a dataframe
    strtodf<-function (list){
      slist<-strsplit(list, ":")
      x<-sapply(slist, FUN= function(x) {x[1]})
      y<-sapply(slist, FUN= function(x) {x[2]})
      df<-data.frame(state=x, island=y, stringsAsFactors = FALSE)
      return(df)
    }
    
    #user defined coloring scheme
    #    Example data for to test solution
    colors<- c("#7aad42","#4a77bb","#f7931e","#d3dfbd","#787878")
    region<-c("washington", "new york", "virginia", "pennsylvania", "ohio")
    states_info<-data.frame(region, colors)
    #    End of example data
    
    #dataframe to hold state names for mapping purposes
    library(maps)
    maplist<-map("state", namesonly = TRUE, plot=FALSE)
    statelist<-strtodf(maplist)  #convert to dataframe
    statelist$row<-as.numeric(rownames(statelist))  #index column
    
    #merge the data from and resort into proper order
    statelist<-merge(statelist, states_info, by.x = "state", by.y="region", sort=FALSE, all.x=TRUE)
    statelist<-statelist[order(statelist$row),]
    
    #plot the map
    maplist<-map("state", fill=TRUE, col=statelist$colors)
    
    0 讨论(0)
  • 2021-01-26 19:43

    Let ggplot2 do the hard work for you:

    library(ggplot2)
    
    read.table(text="State.Code   region St_Abbr Num_Estab  colors
    1          1   alabama      AL     13123 #f7931e
    3          4   arizona      AZ     18053 #f7931e
    4          5   arkansas      AR      9154 #4a77bb
    5          6   california      CA    143937 #787878
    6          8   colorado      CO     21033 #d3dfbd
    7          9   connecticut      CT     17176 #f7931e", 
               stringsAsFactors=FALSE, header=TRUE, comment.char="") -> df
    
    usa_map <- map_data("state")
    
    gg <- ggplot()
    gg <- gg + geom_map(data=usa_map, map=usa_map,
                        aes(long, lat, map_id=region),
                        color="#2b2b2b", size=0.15, fill=NA)
    gg <- gg + geom_map(data=df, map=usa_map,
                        aes(fill=colors, map_id=region),
                        color="#2b2b2b", size=0.15)
    gg <- gg + scale_color_identity()
    gg <- gg + coord_map("polyconic")
    gg <- gg + ggthemes::theme_map()
    gg
    

    0 讨论(0)
提交回复
热议问题