2017-03-09 1 views
0

전체적인 레이블과 다른 글꼴 크기의 레이블을 사용하여 Google지도의 평면 그림을 만들고 싶습니다. 예를 들어, (link)를 블로그 포스트에서 최대 Marchi입니다에 의해 제공되는 코드를 기반으로 다음 코드를 고려 :전체 레이블과 다른 글꼴 크기를 갖는 레이블이있는 Google지도의 플롯 된 그림

# Load the data 
airports <- read.csv("https://raw.githubusercontent.com/jpatokal/openflights/master/data/airports.dat", header = FALSE) 
colnames(airports) <- c("ID", "name", "city", 
    "country", "IATA_FAA", "ICAO", "lat", "lon", 
    "altitude", "timezone", "DST") 

routes <- read.csv("https://github.com/jpatokal/openflights/raw/master/data/routes.dat", header = FALSE) 
colnames(routes) <- c("airline", "airlineID", 
    "sourceAirport", "sourceAirportID", 
    "destinationAirport", "destinationAirportID", 
    "codeshare", "stops", "equipment") 

# Getting the data ready for plotting 
# * For a detailed explanation on setting up the data 
# I suggest consulting Max Marchi's post: 
# http://www.milanor.net/blog/maps-in-r-plotting-data-points-on-a-map/ 
library(plyr) 
departures <- ddply(routes, .(sourceAirportID), "nrow") 
names(departures)[2] <- "flights" 
arrivals <- ddply(routes, .(destinationAirportID), "nrow") 
names(arrivals)[2] <- "flights" 
airportD <- merge(airports, departures, by.x = "ID", 
        by.y = "sourceAirportID") 
airportA <- merge(airports, arrivals, by.x = "ID", 
        by.y = "destinationAirportID") 
airportD$type <- "departures" 
airportA$type <- "arrivals" 

# The final data frame used for plotting 
airportDA <- rbind(airportD, airportA) 

# Get the map of Europe from Google Maps 
library(ggmap) 
map <- get_map(location = 'Europe', zoom = 4) 

# Make a facetted Google map plot 
library(ggplot2) 
facet.gmap <- ggmap(map) + 
    geom_point(aes(x = lon, y = lat, 
    size = sqrt(flights)), 
    data = airportDA, alpha = .5) + 
    facet_wrap(~ type, ncol=2) + 
    theme(legend.position="none") 

# Add an overall label with different font sizes 
library(gtable) 
library(grid) 
facet.gmap.label <- ggplotGrob(facet.gmap) 
facet.gmap.label <- gtable_add_grob(facet.gmap.label, 
      grobTree(textGrob("M", x=0.05, 
         y=0.85,just="left", 
         gp = gpar(fontsize = 14, 
         fontface = "bold")), 
        textGrob("Some label", x=0.18, 
         y=0.68, just="left", 
         gp = gpar(fontsize = 9, 
         fontface = "bold"))), 
        t=1, b=4, l=1, r=4) 

# Save as PDF 
pdf("facet.gmap.label.pdf", 
     width=4.5, 
     height=3.6) 
grid.draw(facet.gmap.label) 
dev.off() 

을 나는이 얻을 :

enter image description here

이를 줄이기 위해 흰색 공백을 제거하고 전체 레이블을 표시합니다. themeplot.margin 매개 변수에서 다른 값을 테스트했으며 plot.margin = unit(c(0.8, 0.4, -3.8, 0.3), "lines") :

를 설정하여 "가장 나쁜"음모를 얻었습니다
# Edit the 'theme' 'plot.margin' parameter 
facet.gmap2 <- facet.gmap + 
theme(plot.margin = unit(c(0.8, 0.4, -3.8, 0.3), "lines")) 

# Add again the overall label with different font sizes 
facet.gmap.label2 <- ggplotGrob(facet.gmap2) 
facet.gmap.label2 <- gtable_add_grob(facet.gmap.label2, 
      grobTree(textGrob("M", x=0.05, 
         y=0.85,just="left", 
         gp = gpar(fontsize = 14, 
         fontface = "bold")), 
        textGrob("Some label", x=0.18, 
         y=0.68, just="left", 
         gp = gpar(fontsize = 9, 
         fontface = "bold"))), 
        t=1, b=4, l=1, r=4) 

# Save as PDF 
pdf("facet.gmap.label2.pdf", 
     width=4.5, 
     height=3.6) 
grid.draw(facet.gmap.label2) 
dev.off() 

결과 :

enter image description here

결론 : 나는 plot.margin에 다른 값을 테스트하는만큼, 난 여전히이 같은 것 내가 필요 음모를 얻을하지 않습니다

enter image description here

은 내가 네브라스카하지만 내 목표이 좋은 생각이 아닌 이미지 편집기 소프트웨어의 도움으로이 마지막/원하는 플롯을 만들어 이러한면 처리 된 Google지도 플롯을 여러 개 만들었습니다. 각각은 전체 레이블을 가지며 레이블은 다른 글꼴 크기를가집니다.

누구나 R에서 마지막 것과 같은 플롯을 만드는 방법에 대한 제안 사항이 있습니까? 미리 감사드립니다.

  • P.S.1 : 위의 그림 주위 이미지 편집기 소프트웨어를 수동으로 그려진 하였다 검은 색 테두리가 나는 흰색 빈 공백 데 문제를 강조 표시합니다.

  • P.S.2 : 제공되는 코드에서 그래픽은 게시 용도로 사용하기 때문에이 그림을 PDF로 내 보냈습니다. 따라서 너무 많은 흰색 공백은 과학 저널에 종종 그림 크기 제한이 있기 때문에 좋은 것이 아닙니다.

답변

2

왜 마진 추가를 자동으로 처리 할 ggtitle을 사용할 수 없습니까?

이 당신이 필요로하는 좌표 정확한 X-Y를 찾는 함께 놀러하지 않고 당신이 원하는 텍스트 출력을 제공한다 :

facet.gmap + 
    ggtitle(expression(bold(M)~scriptstyle("Some Label"))) 

당신이 찾고있는 플롯을 제공합니다.

enter image description here

당신이있을 것 같다 다른 문제는 화면 비율입니다. ggmap (유용하게) coord_fixed 또는 이와 유사한 것을 사용하여 x와 y 거리의 비율이 올바르게 유지되도록합니다.출력의 종횡비 (로 전화 할 때 width ~ height)가 다른 경우 가장 제한적인 치수에 맞게 플롯이 축소되고 다른 곳에 공백이 남습니다. 나는 RStudio의 플롯 창에서이 파일을 보면서 440x287에서 꽤 좋은 비율을 보였다. 대략적인 비율을 유지하고 거기에서부터 땜질을하는 너비와 높이로 시작해보십시오.

+0

@ Mark Peterson에게 감사드립니다. 정말 필요한 플롯을 달성하는 데 정말로 도움이되었습니다! 나는 당신의'ggtitle' 제안에 대해서 하나의 질문을 가지고 있습니다 : "M"과 "Some label"의 폰트 크기를 따로 제어 할 수 있는지 알고 있습니까? 또는 글꼴 크기 비율을 제어 할 수 있습니까? 'M '의 폰트 크기는'theme (plot.title = element_text (size)')에서 제어 할 수 있기 때문에 폰트 크기를 제어하고자'scriptstyle()'에'size' 인자를 추가하려고했습니다. label "하지만 아무 것도 바뀌지 않았습니다이 질문은 더 호기심입니다 언젠가 필요할 수도 있습니다 –

+1

글꼴 크기를 제어하는 ​​방법에 대해'? plotmath'에 더 많은 옵션이 있습니다 .."Some Label "더 작게 만들고 싶다면'textscriptstyle'을 시도해보십시오. 다른 옵션을 가지고 놀아 볼 수도 있지만 그보다 더 세밀한 제어를 알지 못합니다. –

+0

Ok, thanks @ 마크 피터슨. –

관련 문제