2016-12-11 3 views
2

내 특정 문제를 이미 많이 조사했지만 해결책을 찾지 못했습니다. 그러나, 나는 그것을 풀기가 아주 쉽다고 생각하지만, 나는 r을 처음 접한다.r의 국가지도에 위치 점들을 어떻게 그리는가?

  • 내가 원하는 것 : 나는 인도에서 흑백으로 개최 된지도를 계획하고 싶습니다. 그리고 저는 방문한 모든 장소에 점들과 해당 이름을 그려 봅니다. 나는 아래의 코드로 그 모든 것을 할 수 있었다.
  • 내 문제 : 방문한 장소를 플로팅하는 데 간단한 방법으로 코드를 작성하려면 어떻게해야합니까? visit.xvisit.y과 같은 변수를 모두 만들고 싶지 않습니다. 또한, 모든 장소에 대해 geom_pointgeom_text에 대한 코드를 작성해야합니다. 예를 들어 한 번에 여러 장소를 플로팅하려했는데

    visited <- c("New Delhi", "Rishikesh") 
    

는 내가 "미학이 중 길이가 1 인 또는 데이터와 같아야합니다"오류 메시지를 받았습니다.

  • 내 질문 : 어떻게하면 모든 방문한 장소를 하나의 변수에 저장하고 하나의 실행으로 플로팅 할 수 있습니까? 마찬가지로 나는 geom_point에 대해 한 줄만 필요로하고 음모를 꾸미고 싶은 모든 장소에 대해서는 필요하지 않습니다. 그것은 전체에 하나의 데이터를 유지하기 위해 가장 적합한 있도록

    @hrbrmstr 위의 코멘트에 제안으로 은
    #Load required packages 
    library(maps) 
    library(ggmap) 
    library(ggplot2) 
    
    #Dataframe with country relevant information 
    map <- fortify(map(fill = T, plot = F, region = "India")) 
    
    #Places I want to mark on the map 
    visited <- c("New Delhi") 
    visited2 <- c("Rishikesh") 
    visited3 <- c("Agra") 
    
    #Extracting long/lat of the places 
    visit.x <- geocode(visited)$lon 
    visit.y <- geocode(visited)$lat 
    visit.x2 <- geocode(visited2)$lon 
    visit.y2 <- geocode(visited2)$lat 
    visit.x3 <- geocode(visited3)$lon 
    visit.y3 <- geocode(visited3)$lat 
    
    #Defining font 
    font = c("Courier") 
    font.size = 3 
    
    #Specifing the look of the map with ggplot2 
    map_india <- ggplot(data = map, aes(x = long, y = lat, group = group)) + 
        geom_polygon(fill = "white") + 
        geom_path(colour = "black") + 
        theme(panel.background = element_rect(fill = "#000000"), 
          panel.grid.major = element_blank(), 
          panel.grid.minor = element_blank(), 
          axis.ticks = element_blank(), 
          axis.text.y = element_blank(), 
          axis.text.x = element_blank(), 
          axis.title.x = element_blank(), 
          axis.title.y = element_blank()) 
    
    #Plotting the places I want on the map with labels 
    map_india <- map_india + 
        geom_point(aes(x = visit.x, y = visit.y)) + 
        geom_text(data = NULL, x = visit.x - 1, y = visit.y + 0.2, label = "New Delhi", size = font.size, family = font) + 
        geom_point(aes(x = visit.x2, y = visit.y2)) + 
        geom_text(data = NULL, x = visit.x2 - 1, y = visit.y2 + 0.2, label = "Rishikesh", size = font.size, family = font) + 
        geom_point(aes(x = visit.x3, y = visit.y3)) + 
        geom_text(data = NULL, x = visit.x3, y = visit.y3 + 0.5, label = "Agra", size = font.size, family = font) + 
        coord_fixed(0.8) 
    
    #Creating pdf 
    pdf("India.pdf", height = 11.69, width = 16.53) 
    print(map_india) 
    dev.off() 
    
+0

ggplot2 geoms에 데이터 프레임을 전달하여 원하는 동작을 얻습니다. 컬럼이있는 데이터 프레임을 만들고'data' (대문자 인'NULL')에 넣고 'x','y' 및'label'에 컬럼 이름을 사용하면됩니다. ggplot2 예제를 실행하고 조금 더 배우는 것이 더 좋을 것입니다. 궁극적으로 차트를 작성하는 것은 논리적이고 직접적인 방법이지만, 거기에 도달하기 위해서는 약간의 시행 착오가 필요합니다. ggplot2 geoms : heart : data.frames를 기억하십시오. – hrbrmstr

답변

2

, ggplot2는 data.frames 작동하도록 설계되었습니다. 그래서 실제로 이렇게하면 너무 코드를 많이 단순화 : 당신이 원하는대로

library(tidyverse) # for ggplot2 and `%>%` 
library(ggmap) 
library(ggrepel) # for geom_text_repel, though adjust overlaps manually if you prefer 

cities <- data_frame(city = c("New Delhi", "Rishikesh", "Agra")) %>% # start data.frame 
     mutate_geocode(city) # use ggmap function to add lon/lat columns 

cities 
#> # A tibble: 3 × 3 
#>  city  lon  lat 
#>  <chr> <dbl> <dbl> 
#> 1 New Delhi 77.20902 28.61394 
#> 2 Rishikesh 78.26761 30.08693 
#> 3  Agra 78.00807 27.17667 

box <- geocode('India', output = 'more') # get lon/lat for bounding box 

box 
#>  lon  lat type  loctype address north south  east 
#> 1 78.96288 20.59368 country approximate india 35.5087 6.753516 97.39556 
#>  west country 
#> 1 68.16289 India 

get_stamenmap(bbox = c(left = box$west, # get background tiles, set bounding box 
         bottom = box$south, 
         right = box$east, 
         top = box$north), 
       maptype = 'toner-background', # set map style 
       zoom = 5) %>% 
    ggmap(extent = 'device') + # note switch from %>% to + as moves to ggplot 
    geom_point(aes(x = lon, y = lat), data = cities) + # add points 
    geom_text_repel(aes(x = lon, y = lat, label = city), data = cities) # add labels 

india map with points and labels

을 조정합니다.

관련 문제