How to make sure text title is inside the polygon object?

Viewed 1684

I am making a map plot, where I want to put a small text label inside every state. My current problem is that the text goes outside the state limits, so it doesn't look nice: enter image description here

I tried using mean, median, centroids and so on.

What I want is every text to be completely inside or outside the polygon , like here: enter image description here (image from http://www.businessinsider.com/map-what-100-is-actually-worth-in-your-state-2015-7?IR=T)

I use the following code to generate my picture:

library(maps)
library(dplyr)
library(ggplot2)

#data 
mapbase <- map_data("state.vbm")    
data(state.vbm.center)
df <- state.vbm.center %>% as.data.frame() %>% 
  mutate(region = unique(mapbase$region) ) %>%   full_join(mapbase) 


#actual plotting
cnames <- aggregate(cbind(long, lat) ~ region, data=df, FUN=median)
gmap<- 
  ggplot()+
  geom_polygon( data=df2,
                aes(long, lat, group = region, fill = somevalue,alpha=0.3)) + 
   coord_fixed() + 
  theme_void() + 
  geom_text(data=cnames, aes( fontface=2 ,cnames$long, cnames$lat , label = "text"
  ), color= "black" ,size=3,check_overlap = T, position=position_jitter(width=3, height=3)  )  +

  scale_fill_gradient(low="red",high="blue")

Thanks so much for you hints!

1 Answers
Related