我需要按ggplot2中的区域比较乌克兰城市。 但是它们全部以相同的大小绘制。
你能帮我吗?
我使用以下代码:
library(ggplot2)
cities <- read.csv("https://raw.githubusercontent.com/savchukidze/maps/master/cities.csv", stringsAsFactors = F)
png("compare_cities.png", height = 3000, width = 2500)
ggplot()+
geom_polygon(data = cities, aes(long, lat, group = group),
color = "black", size = 2.5, fill = "grey", alpha = 1)+
facet_wrap(~city, scales = "free")
dev.off()
答案 0 :(得分:1)
这有点棘手,因为您需要每个面板都具有“可用”空间,但不能将其与coord_fixed
结合使用。
您需要将它们全部放置在比例尺上进行坐标调整。
library(tidyverse)
cities %>%
group_by(city) %>%
mutate(long=long-mean(long), lat=lat-mean(lat)) %>%
ggplot(aes(long, lat, group=city)) +
geom_polygon() +
facet_wrap(~city)
答案 1 :(得分:1)
It is a bit messy, but you could do something like this to plot invisible points at the maximum range for each city, to keep the scales the same...
library(tidyverse)
ranges <- cities %>%
group_by(city) %>%
summarise(minlat=min(lat), #get limits for each city
maxlat=max(lat),
minlon=min(long),
maxlon=max(long)) %>%
mutate(rangelat=maxlat-minlat, #calculate range required for each
rangelon=maxlon-minlon,
centrelat=(maxlat+minlat)/2, #calculate centre point of plot
centrelon=(maxlon+minlon)/2) %>%
ungroup() %>%
mutate(bottom=centrelat-max(rangelat)/2,#calculate box size based on max range
top=centrelat+max(rangelat)/2,
left=centrelon-max(rangelon)/2,
right=centrelon+max(rangelon)/2)
ggplot()+
geom_polygon(data = cities, aes(long, lat, group = group),
color = "black", size = 2.5, fill = "grey", alpha = 1)+
geom_point(data=ranges, aes(x=left,y=bottom), alpha=0)+ #invisible bottom left point
geom_point(data=ranges, aes(x=right,y=top),alpha=0)+ #invisible top right point
facet_wrap(~city,scales = "free")