如何在R中向地图添加图例?

时间:2017-04-26 17:25:58

标签: r ggplot2 ggmap

stateCoords列:State,Abbr,Longitude,Latitude,Region。

西,中西部,西南,东南,东北5个地区,西部1个,中西部2个,等等。

# Declaration of Region Colors: West, Midwest, Southwest, Southeast, Northeast
regionColors <- c("#f76f6a","#f59846", "#C7E363", "#f9dc6d", "#58b2c3")

# Import state coords
stateCoords <- read.csv("stateCoords.csv", header=TRUE)

# Generate US Map
# Retrieve map of the U.S. (Alaska and Hawaii excluded)
map.data <- map_data("state")
# Create the map
m =  ggplot(map.data) + geom_map(aes(map_id = region), map = map.data, fill 
= "white", color = "grey20", size = 0.25) +
  expand_limits(x = map.data$long, y = map.data$lat) + 
  theme(axis.line = element_blank(), axis.text = element_blank(), axis.ticks 
= element_blank(),
        axis.title = element_blank(), panel.background = element_blank(), panel.border = element_blank(),
    panel.grid.major = element_blank(), plot.background = element_blank(),
    plot.margin = unit(0 * c(-1.5, -1.5, -1.5, -1.5), "lines")) 
# plot the map
plot(m)

x = NULL
y = NULL
col = NULL
for (i in 1:nrow(stateCoords)) {
  r = stateCoords[i,]
   x1 = rep(r$Longitude, r$catTweets1)
   y1 = rep(r$Latitude, r$catTweets1)
   x = c(x, x1)
   y = c(y, y1)

   stateColor = regionColors[r$RegionNum]

   nextCol = rep(stateColor, r$catTweets1)

   col = c(col, nextCol)
}


x = x + rnorm(length(x), sd = .27)
y = y + rnorm(length(y), sd = .27)

points = data.frame(x = x, y = y)


# add the points to the map
m2 = m + geom_point(data = points,  aes(x = x, y = y), size = 3, alpha = 
0.3, color = col)
# plot the map with the points
plot(m2)

有人可以帮我在左下角添加一个传奇吗?我想要一个彩色圆点和相应的区域。例如,

#f76f6a colored dot   West
#f59846 colored dot   Midwest

https://i.stack.imgur.com/fmCGC.png

dput(stateCoords) https://pastebin.com/0J4ZQ89U 信息量很长,所以我把它放在一个pastebin中......

我尝试查找资源,但最终比以前更加困惑。我确实查看了可用的ggmap.pdf文件。

0 个答案:

没有答案