[英]How to plot rectangles of equal width onto a map in ggplot
我有兩個相關指標的全球人口數據,並想為 map 上的每個位置制作迷你條形圖。 由於我每個人口只需要兩個條形圖,並且它們都有相似的比例,因此我計划使用 geom_rect() 僅對它們進行 plot。 但是,條形寬度並不一致,即使在相同人群的兩個條形之間也是如此。
這是我用於此的簡化 R 代碼:
library("ggplot2")
theme_set(theme_bw())
library("sf")
library("rnaturalearth")
library("rnaturalearthdata")
library("rgeos")
world <- ne_countries(scale = "medium", returnclass = "sf")
pop_data <- data.frame(long=c(-63,-68,-108,86,64,129,114,174,143,90,64,-21,40,-4,38.7),
lat=c(-23,3,29,51,64,63,32,-41,-4,24,26,64,61,40,39),
measA=c(10,10,10,10,10,10,10,10,10,10,10,10,10,10,10),
measB=c(10,10,10,10,10,10,10,10,10,10,10,10,10,10,10))
ggplot(data = world) +
geom_sf()+
geom_rect(data = pop_data,fill="blue",
aes(xmin = long-2,
xmax = long-1,
ymin = lat,
ymax = lat+measA))+
geom_rect(data = pop_data,fill="red",
aes(xmin = long+1,
xmax = long+2,
ymin = lat,
ymax = lat+measB))+
theme(axis.title.x=element_blank(),axis.title.y=element_blank())
在最終的 plot 中,這些條將具有不同的高度,但這只是為了說明寬度差異。 誰能解釋為什么寬度不同,以及如何解決這個問題? 我也願意接受在 map 上制作簡單迷你條形圖的其他解決方案。 我確實看到了制作迷你條形圖的其他解決方案,但其中大多數使用不再有效的 ggplot function。
我建議您可以選擇一個繪制線條並通過size=
控制寬度的幾何圖形 - 它可能會讓您看起來更加一致。 正如其他人提到的,嘗試使用不同的圖形導出,因為jpeg()
、 png()
和pdf()
的渲染器可能不同。 這是geom_segment()
和geom_linerange()
的兩個示例。 請注意,我建議您pop_data
dataframe 並收集/熔化/pivot_longer ...將measA
和measB
列放在一起,以簡化您的ggplot()
調用並避免重復幾何。 你會看到我用geom_linerang()
做到了這一點,但由於躲避與 geom_segment 無法正常工作,我在不修改pop_data
的情況下展示了它。
ggplot(data = world) +
geom_sf() +
geom_segment(
data=pop_data, color='blue',
aes(x= long-1, xend=long-1, y= lat, yend=lat+measA),
size=1.2) +
geom_segment(
data=pop_data, color='red',
aes(x= long+1, xend=long+1, y= lat, yend=lat+measB),
size=1.2) +
theme(axis.title.x=element_blank(),axis.title.y=element_blank())
如前所述,我在這里使用dplyr
和tidyr::gather()
修改pop_data
,然后只需要調用geom_linerange()
。 我更喜歡這個解決方案,但結果非常相似:
pop_data1 <- pop_data %>%
gather('measure', 'pop', -c(long,lat))
ggplot(data = world) +
geom_sf() +
geom_linerange(
data=pop_data1,
aes(x= long, ymin= lat, ymax=lat+pop,
color=measure, group=measure),
size=1.2, position=position_dodge(5)) +
scale_color_manual(values=c('red','blue')) +
theme(axis.title.x=element_blank(),axis.title.y=element_blank())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.