我在R中使用ggmap包,我對地理空間數據可視化相對比較陌生。我有一個11個經緯度對的數據框,我想在地圖上繪製,每個都有一個標籤。這裏是虛擬數據:動態數據點標籤在ggmap中定位
lat<- c(47.597157,47.656322,47.685928,47.752365,47.689297,47.628128,47.627071,47.586349,47.512684,47.571232,47.562283)
lon<-c(-122.312187,-122.318039,-122.31472,-122.345345,-122.377045,-122.370117,-122.368462,-122.331734,-122.294395,-122.33606,-122.379745)
labels<-c("Site 1A","Site 1B","Site 1C","Site 2A","Site 3A","Site 1D","Site 2C","Site 1E","Site 2B","Site 1G","Site 2G")
df<-data.frame(lat,lon,labels)
現在我用annotate
創建數據點標籤和這些繪製在地圖上;
map.data <- get_map(location = c(lon=-122.3485,lat=47.6200),
maptype = 'roadmap', zoom = 11)
pointLabels<-annotate("text",x=uniqueReach$lon,y=c(uniqueReach$lat),size=5,font=3,fontface="bold",family="Helvetica",label=as.vector(uniqueReach$label))
dataPlot <- ggmap(map.data) +
geom_point(data = uniqueReach,aes(x = df$lon, y = df$lat), alpha = 1,fill="red",pch=21,size = 6) + labs(x = 'Longitude', y = 'Latitude')+pointLabels
這將產生數據點
的情節一樣,你可以看到,有四處重疊(-122.44,47.63)兩個數據點,其標籤也有重疊。現在,我可以手動爲每個標籤點添加一個移位,以防止標籤重疊(請參閱this post),但當我需要爲不同的經緯度對生成很多這些圖時,這不是一個好方法。
有沒有一種方法可以自動保持數據標籤不重疊?我意識到標籤是否重疊取決於實際的身材尺寸,所以我打算在需要時將身材尺寸固定在某個尺寸。提前感謝您的任何見解!
編輯
使用桑迪Mupratt
# Defining function to draw text boxes
draw.rects.modified <- function(d,...){
if(is.null(d$box.color))d$box.color <- NA
if(is.null(d$fill))d$fill <- "grey95"
for(i in 1:nrow(d)){
with(d[i,],{
grid.rect(gp = gpar(col = box.color, fill = fill,alpha=0.7),
vp = viewport(x, y, w, h, "cm", c(hjust, vjust=0.25), angle=rot))
})
}
d
}
# Defining function to determine text box borders
enlarge.box.modified <- function(d,...){
if(!"h"%in%names(d))stop("need to have already calculated height and width.")
calc.borders(within(d,{
w <- 0.9*w
h <- 1.1*h
}))
}
給出的答案生成該地塊修改後的代碼如下:
dataplot<-ggmap(map.data) +
geom_point(data = df,aes(x = df$lon, y = df$lat),
alpha = 1, fill = "red", pch = 21, size = 6) +
labs(x = 'Longitude', y = 'Latitude') +
geom_dl(data = df,
aes(label = labels),
list(dl.trans(y = y + 0.3), "boxes", cex = .8, fontface = "bold"))
這是一個非常更多r可靠的情節,但有一個突出的問題。您會注意到標籤「Site 1E」開始重疊與「Site 1A」關聯的數據點。直接標籤是否有處理標籤重疊屬於另一個標籤的數據點的方法?
我對此有一個最後的問題是如何使用這種方法繪製幾個重複的標籤。假設標籤data.frame都是一樣的:
df$labels<-rep("test",dim(df)[1])
當我使用相同的代碼,directlabels刪除重複的標籤名稱:
但我想每個數據點有一個標籤「測試」。有什麼建議麼?
的directlabels包是有一個很好的工具。感謝您的建議。使用'list(dl.trans(y = y + 0.2)'是關鍵在於對標籤位置進行一些控制,同時仍然使用geom_dl的功能。 除了「Site 1A」標籤與底層圖表中的單詞「Seattle」重疊。有關解決此問題的任何建議將非常感謝。 – Archimeow
@JMeo,我已添加編輯 –
我已使用您的出色解決方案編輯了代碼。關於如何避免文本框與任何相鄰數據點重疊,以及如何繪製不同數據點之間重複的標籤,我跟進了一些問題(請參閱我的編輯)。在學習如何使用'directlabels'時,再次感謝您的支持 – Archimeow