R code to Generating map of US states with specific colors

后端 未结 2 793
夕颜
夕颜 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: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
    

提交回复
热议问题