2

I'm doing a map of China biggest cities in terms of population using ggplot2.

The initial dataset was in a shapefile therefore I used readOGR to convert the data into a Spatial vector object and then using fortify I turned the map into a dataframe so I could use ggplot2.

My main problem was that by using geom_label the labels kept overlapping each other so I changed to geom_label_repel but now some of the cities labels are placed outside the map. Is there any way of forcing geom_label_repel to keep the labels inside the map?

Cheers!

library(rgdal)
library(raster)
library(ggplot2)

ctry_spdf <- readOGR(dsn=".",layer="COUNTRIES_ALL",verbose=F)
china<-subset(ctry_spdf,ctry_spdf@data$CNTRY_NAME=="China")
cities <- readOGR(dsn=".",layer="cities")

chinese_cities <- intersect(cities,china)

china_df<-fortify(china, region="OBJECTID")
china_ff <- merge(china_df, china@data, by.x = "id", by.y = "OBJECTID")

cities_df <- as(chinese_cities, "data.frame") 

plot_china<- c(geom_polygon(data=china_ff, aes(long, lat, group = group)))

plot_cities<-c(geom_point(data=cities_df,aes(x=POINT_X, y=POINT_Y,col="red")))

#plot_labels<-c(geom_label(data=cities_df,aes(x=POINT_X, y=POINT_Y,label=CITY_NAME))) --previous 
methodology overlapping

plot_labels<-c(geom_label_repel(
arrow = arrow(length = unit(0.03, "npc"), type = "closed", ends = "first"),
force = 10,
data=cities_df,aes(x=POINT_X, y=POINT_Y,label=CITY_NAME) ) )

ggplot()+plot_china+plot_cities+plot_labels+coord_equal() + labs(title = "China", x = "long", y = 
"lat", color = "City") +scale_color_manual(labels = c("Big Cities"), values = c("red")) 

See map here

lber
  • 23
  • 5

0 Answers0