连接地图中的两个特定点

时间:2017-06-03 18:55:33

标签: r ggplot2

使用这个我们有一个包含数据点的地图:

加载数据:

countries <- structure(list(country = structure(c(5L, 6L, 3L, 4L, 10L, 8L, 
11L, 7L, 1L, 13L, 9L, 12L, 2L), .Label = c("Australia", "China", 
"France", "Georgia", "India", "Ireland", "Malaysia", "Poland", 
"Qatar", "Singapore", "South Africa", "Spain", "USA"), class = "factor"), 
    Latitude = c(20.593684, 53.142367, 46.227638, 32.165622, 
    1.352083, 51.919438, -30.559482, 4.210484, -25.274398, 37.09024, 
    25.354826, 40.463667, 35.86166), Longitude = c(78.96288, 
    -7.692054, 2.213749, -82.900075, 103.819836, 19.145136, 22.937506, 
    101.975766, 133.775136, -95.712891, 51.183884, -3.74922, 
    104.195397), Value = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    2L, 1L, 2L, 2L)), .Names = c("country", "Latitude", "Longitude", 
"Value"), class = "data.frame", row.names = c(NA, -13L))

使用this的地图绘制代码:

library(maps)
 library(ggplot2)
 base_world <- map_data("world")
p <- ggplot() + 
   geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
   geom_point(data=countries, aes(x=Longitude, y=Latitude, colour="blue"), size=5, alpha=I(0.7))

我尝试连接点。示例我想要连接: 西班牙 - 中国 美国 - 西班牙

到目前为止我所拥有的是:

p + geom_line(data=countries, aes(x=Longitude, y=Latitude), color="black", size=1)

这将连接地图中的所有点。是否可以仅连接特定值并在地图中的数据点中显示值列数?

这也是我在每个点(值)

中尝试过的数字标签
p + geom_text(aes(label=countries$Value),hjust=0, vjust=0, aes(x=Longitude, y=Latitude))
Error: ggplot2 doesn't know how to deal with data of class uneval

包含两个以上点的列表示例(每行是不同的连接):

("USA", "Spain","China")
("Australia", "Poland")

1 个答案:

答案 0 :(得分:2)

您可以根据要连接的点获取子集;

link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

base_world <- map_data("world")
p <- ggplot() + 
      geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
      geom_line(data=link1, aes(x=Longitude, y=Latitude), color="red", size=1) +
      geom_line(data=link2, aes(x=Longitude, y=Latitude), color="green", size=1) +
      geom_point(data=countries, aes(x=Longitude, y=Latitude), colour = "cyan", size=5, alpha=I(0.7)) + #set the color outside of `aes`
      theme(text = element_text(size=20), legend.position="none")  #remove the legend  

你的情节看起来像是:

> p

MAP-ggplot2-worldmap-connections-p

您可能需要稍微玩一下格式化问题。