ggplot centered names on a map

前端 未结 4 1745
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 03:27

I\'m attempting to use ggplot2 and maps to plot the names of the counties in NY state. My approach was to find the means of latitude and longitude by county (I assume this

4条回答
  •  时光取名叫无心
    2020-11-29 04:22

    Since you are creating two layers (one for the polygons and the second for the labels), you need to specify the data source and mapping correctly for each layer:

    ggplot(ny, aes(long, lat)) +  
        geom_polygon(aes(group=group), colour='black', fill=NA) +
        geom_text(data=cnames, aes(long, lat, label = subregion), size=2)
    

    Note:

    • Since long and lat occur in both data frames, you can use aes(long, lat) in the first call to ggplot. Any mapping you declare here is available to all layers.
    • For the same reason, you need to declare aes(group=group) inside the polygon layer.
    • In the text layer, you need to move the data source outside the aes.

    Once you've done that, and the map plots, you'll realize that the midpoint is better approximated by the mean of range, and to use a map coordinate system that respects the aspect ratio and projection:

    cnames <- aggregate(cbind(long, lat) ~ subregion, data=ny, 
                        FUN=function(x)mean(range(x)))
    
    ggplot(ny, aes(long, lat)) +  
        geom_polygon(aes(group=group), colour='black', fill=NA) +
        geom_text(data=cnames, aes(long, lat, label = subregion), size=2) +
        coord_map()
    

    enter image description here

提交回复
热议问题