Reputation: 59
I need compare ukrainian cities by area in ggplot2. But all of they plot in the same size.
Can you help me?
I use this code:
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()
Upvotes: 2
Views: 173
Reputation: 462
This is a little tricky, because you need each panel to have "free" space, but cannot combine that with coord_fixed
.
You'll need to place them all on the scale for coordinates.
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)
Upvotes: 1
Reputation: 18425
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")
Upvotes: 1