Home > database >  Adding labels to a map with ggplot
Adding labels to a map with ggplot

Time:12-11

I did a map with ggplot() and I wanted to add labels to the map, or an interactive thing so that when I hover over the state area it gives me the name of it. I looked for tips in Stackoverflow however it is not working.
Do you have any suggestions?

How my data looks like

scaling_map <-ggplot(pop_usa, aes(long,lat))   
geom_polygon(aes(group= group, fill = estimated_pop_2020) ,color="black")  
theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.y=element_blank(), 
axis.text.y=element_blank(), axis.ticks.y=element_blank(),plot.title = element_text(face = "bold",hjust = 0.5))  
  ggtitle("Estimated population by state")  
  scale_fill_gradient(name ="Estimated population (log10)" ,low = "#FFFFCC" , high = "#336600")  
  geom_sf_text(aes(label = state))
  coord_map()

Here is the message that I got when I ran it:

Error in `geom_sf_text()`:
! Problem while computing stat.
ℹ Error occurred in the 2nd layer.
Caused by error in `compute_layer()`:
! `stat_sf_coordinates()` requires the following missing aesthetics: geometry
Run `rlang::last_error()` to see where the error occurred.

CodePudding user response:

with view to the error

'stat_sf_coordinates()' requires the following missing aesthetics: geometry

try, instead of geom_polygon:

geom_sf(aes(group = group, fill = estimated_pop_2020, geometry = geometry) ,color="black")

and supply the geometry to geom_sf_text like so:

geom_sf_text(aes(label = state, geometry = geometry)) ## see note

note: unless the geometry column of your spatial dataframe pop_usa is named differently from the default "geometry"

CodePudding user response:

It returns data frame , I tried geom_text and geom_label but none of them worked. Here is the error that I got : Error in geom_point(): ! mapping must be created by aes() However I don't understand why i get this because I actually included the aes argument in the function `scaling_map <-ggplot(pop_usa, aes(long,lat))

  • geom_polygon(aes(group = group, fill = estimated_pop_2020 ) ,color="black")  
    
  • theme(axis.title.x=element_blank(), axis.text.x=element_blank(), axis.ticks.x=element_blank(), axis.title.y=element_blank(), 
    
  •       axis.text.y=element_blank(), axis.ticks.y=element_blank(),plot.title = element_text(face = "bold",hjust = 0.5))  
    
  • ggtitle("Estimated population by state")  
    
  • scale_fill_gradient(name ="Estimated population (log10)" ,low = "#FFFFCC" , high = "#336600")  
    
  • geom_point(pop_usa, aes(x=long, y=lat, group=group, size=values))  
    
  • geom_text(pop_usa, aes(x=long, y=lat, group=group, label=state), size = 3, hjust=0, vjust=-1)  
    
  • coord_map()`        
    
  • Related