我想使用ggplot将饼图绘制到投影地图上。但是,饼图可能会由于投影而变形。有谁知道我如何在不失真的情况下绘制饼图?示例代码如下,谢谢。
lib = c("ggplot2","scatterpie")
lapply(lib, library, character.only=TRUE)
pie = data.frame(
lon=c(-5.0,-3.5,-5.5,5.0),
lat=c(50.0,50.2,50.1,50.5),
A=c(0.25,0.75,0,0.25),
B=c(0.75,0.10,0,0.75),
C=c(0,0.15,1,0),
radius=0.05)
world = map_data("world", resolution=0)
ggplot(data=world, aes(x=long, y=lat, group=group)) +
geom_polygon(data=world, aes(x=long, y=lat, group=group), fill="darkseagreen", color="black") +
coord_map(projection = "mercator",xlim=c(-7.0,-2.0), ylim=c(49,52)) +
geom_scatterpie(aes(x=lon, y=lat, r=0.15), data=pie, cols=c("A","B","C"), color="black", alpha=0.9) +
ylab("Latitude\n") + xlab("Longitude") +
theme(
panel.background = element_rect(fill="lightsteelblue2"),
panel.grid.minor = element_line(colour="grey90", size=0.5),
panel.grid.major = element_line(colour="grey90", size=0.5),
legend.position = "top")
答案 0 :(得分:1)
您可以使用annotation_custom
来解决坐标比的差异。请注意,它仅适用于笛卡尔坐标(不包括coord_map()
),但是只要您可以使用coord_quickmap()
,以下解决方案就会起作用:
步骤1 。使用coord_quickmap()
而不是coord_map()
创建基础图。隐藏了较小的网格线以模仿后者的外观。否则,它与您上面使用的相同:
p <- ggplot(data = world, aes(x=long, y=lat, group=group)) +
geom_polygon(fill = "darkseagreen", color = "black") +
coord_quickmap(xlim = c(-7, -2), ylim = c(49, 52)) +
ylab("Latitude") +
xlab("Longitude") +
theme(
panel.background = element_rect(fill = "lightsteelblue2"),
panel.grid.minor = element_blank(),
panel.grid.major = element_line(colour = "grey90", size = 0.5),
legend.position = "top")
第2步。创建饼图注释:
pie.list <- pie %>%
tidyr::gather(type, value, -lon, -lat, -radius) %>%
tidyr::nest(type, value) %>%
# make a pie chart from each row, & convert to grob
mutate(pie.grob = purrr::map(data,
function(d) ggplotGrob(ggplot(d,
aes(x = 1, y = value, fill = type)) +
geom_col(color = "black",
show.legend = FALSE) +
coord_polar(theta = "y") +
theme_void()))) %>%
# convert each grob to an annotation_custom layer. I've also adjusted the radius
# value to a reasonable size (based on my screen resolutions).
rowwise() %>%
mutate(radius = radius * 4) %>%
mutate(subgrob = list(annotation_custom(grob = pie.grob,
xmin = lon - radius, xmax = lon + radius,
ymin = lat - radius, ymax = lat + radius)))
第3步。将饼图添加到基础图中:
p +
# Optional. this hides some tiles of the corresponding color scale BEHIND the
# pie charts, in order to create a legend for them
geom_tile(data = pie %>% tidyr::gather(type, value, -lon, -lat, -radius),
aes(x = lon, y = lat, fill = type),
color = "black", width = 0.01, height = 0.01,
inherit.aes = FALSE) +
pie.list$subgrob