I apologize because I am quite certain this is a basic question. All I want to do is create a very simple choropleth map in R using the maps package. This is my first attempt at mapping any data in R.
My geography is the lower 48 states including DC. Here are the first few rows of the dataset I want开发者_Go百科 to plot.
> head(choro, n=7)
AL AR AZ CA CO CT DC
"red" "red" "red" "blue" "blue" "blue" "red"
When I attempt to plot a basic map:
map("state",
regions = names(choro),
lty = 1, lwd =1,
boundary=TRUE,
fill=TRUE,
col=choro)
The attached image is what I see. I am new to R, but I imagine the states that are not filled in did not merge correctly, although, I believe I am using 'standard' state abbreviations.
What am I doing wrong!/need to fix?
Any help will be very much appreciated.
If you take out the regions=names(choro), you will get a more completely filled map. If you want the items that are probably missing from the choro vector to be drawn then why not substitute "white" as the color?
If you need a more complete answer then provide a full copy of choro.choro <- c( "red", "red", "red" ,"blue" ,"blue", "blue", "red")
require(maps)
data(state)
names(choro) <-names(state)[1:7]
map("state", lty = 1, lwd =1,
boundary=TRUE, fill=TRUE,
col=choro)
See attached graphic:
Related question here: Choropleth mapping issue in R And tutorial here: http://www.thisisthegreenroom.com/2009/choropleths-in-r/
As mentioned previously, you'll want to merge your colors with the regions that are plotted. The second link above shows a technique to match state abbreviations with the full state names that R wants/needs to use the maps package. Depending on where your choro
data is coming from, it may be easiest to replace the state abbreviations with full state names before reading into R. The other thing of consequence to note is that there are 63 state objects that are plotted. For example, New Yorsk has a few different objects. Mapping to these duplicates will be necessary for a complete looking map.
I would recommend making two calls to the map
function - the first to plot your fill, the second to add a different outline. For example:
# Extract mapnames for States
mapnames <- data.frame(
state = map("state",plot=FALSE)[4]$names
, col = sample(c("pink", "purple", "lavender", "blue"), 63, replace = TRUE)
)
#Plot the colors
map("state", regions = mapnames$state, col = mapnames$col, fill = TRUE, lty = 1, lwd= 1)
#Plot the outlines
map("state", regions = mapnames$state, col = "black", fill = FALSE, add = TRUE, lty = 1, lwd = 1)
You can also take a look at the map_data()
function in ggplot2
for other examples of merging data to create choropleth maps easily.
精彩评论