1

从这里使用这个不错的代码:

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))
link1 <- countries[countries$country %in% c("USA", "Spain","China"), ]
link2 <- countries[countries$country %in% c("Australia", "Poland"), ]

library(ggplot2)
library(maps)
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

我想在 geom_point 旁边显示该值。所以我尝试了 geom_text 使用以下内容:

p+geom_text(aes(label=countries$Value,x=Longitude, y=Latitude),hjust=0, vjust=0) 

但我收到此错误:

Error in eval(expr, envir, enclos) : object 'Longitude' not found
4

2 回答 2

3

试试这个:

p <- ggplot() + 
  geom_polygon(data=base_world, aes(x=long, y=lat, group=group)) +
  geom_line(data=link1, aes(x=Longitude, y=Latitude), color="blue", 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 
  annotate("text", x = countries$Longitude, y=countries$Latitude, label = countries$Value, hjust = 2, colour = "purple") + 
  annotate("text", x = countries$Longitude, y=countries$Latitude, label = countries$country, hjust = -0.1, colour = "red") #if you also want name of countries

这将是情节:

> p


PS我更喜欢annotate作为geom_text个人喜好,但如果你想使用它,那么下面的作品(在定义坐标时应该参考数据框):

p+geom_text(aes(label=countries$Value,x=countries$Longitude, y=countries$Latitude),hjust=0, vjust=0) 

您可能需要考虑使用不同的值,因为文本可能不清晰。

于 2017-06-05T20:21:31.287 回答
1

您缺少以下data参数geom_text

p + geom_text(data = countries, aes(label=Value, x=Longitude, y=Latitude), hjust=0, vjust=0)
于 2017-06-05T21:45:30.033 回答