0

I have a dataset with some statistics for each ZIP area in the U.S.

I would like to create a map in which each area has a different color based on a statistic, or with some circles showing the density in the zone.

I tried to install the usa package and I used the zipcodes function to create a new table, that I left joined to my dataset by the zipcode. I then wrote this ggplot code:

to_map %>%
  ggplot(aes(x = long, y = lat, fill=my_stat)) + 
  geom_polygon(color = "black", size = 0.09) + 
  scale_fill_gradient(low = "yellow", high = "dark green") +
  ggthemes::theme_map() + 
  theme(legend.background=element_rect(fill = alpha("white", 0.5))) 

But I obtain some weird drawing that makes no sense: enter image description here

Does anyone know how to fix it?

Abaco
  • 1
  • 1
  • 2
    I wonder if you need a `group` specified, for instance if each zip has its own outline. It looks like data points from different shapes are being plotted sequentially. – Jon Spring Dec 07 '22 at 20:05
  • 2
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. I concur that you need to specify the proper group. But since we have no idea what the data actually looks like, it's hard to say what the right group may be. – MrFlick Dec 07 '22 at 20:13
  • 1
    using geom_polygon() for mapping required a numeric grouping variable to call for each shape you want to draw on the map, such as the shape of a state. The group is added to the mapping aes(). See https://ggplot2-book.org/maps.html?q=geom_polyson#polygonmaps. This grouping will prevent the mapping of the angular shapes in your example. – Susan Switzer Dec 07 '22 at 22:56

0 Answers0