R code to Generating map of US states with specific colors

后端 未结 2 804
夕颜
夕颜 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)
    

提交回复
热议问题