0
votes

I have a shapefile of all districts in a country. The attribute table contains all kinds of information about each district. My goal is to simply plot the map and shade each district polygon by the values of one variable in the attribute tables (called index).

My current code is:

ggplot() +
  geom_polygon(data=districts, aes(x=long,y=lat,group=group,
 fill=districts@data$index), fill=NA, color='grey',size=.5) +
  coord_equal() + theme_minimal() + 
  theme(panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), 
        axis.line = element_blank(), 
        axis.text.x = element_blank(), 
        axis.text.y = element_blank(),  
        axis.ticks = element_blank(), 
        axis.title.x = element_blank(),  
        axis.title.y = element_blank(),
        legend.position = 'bottom',
        legend.title=element_text(size=20) , 
legend.text=element_text(size=10)) 

However, this produces the bare district map with no filling by attribute. I tried a variation with the basemap details in the higher-level ggplot argument and the fill variable in geom_polygon(), but this gives the error "Error: Aesthetics must be either length 1 or the same as the data (1647057): fill".

ggplot(data=districts, aes(x=long,y=lat,group=group), 
color='grey', size=.5) +
  geom_polygon(fill=districts@data$index) +
  coord_equal() + theme_minimal() + 
  theme(panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(), 
    axis.line = element_blank(), 
    axis.text.x = element_blank(), 
    axis.text.y = element_blank(),  
    axis.ticks = element_blank(), 
    axis.title.x = element_blank(),  
    axis.title.y = element_blank(),
    legend.position = 'bottom',
    legend.title=element_text(size=20) , legend.text=element_text(size=10))

What am I doing wrong? Any help appreciated.

1
Could you provide some data to make a reproducible example ?Boidot
Sure. What is the best way to share the data? Thanksmosquitonomics

1 Answers

0
votes

Try this. tidy() function comes with broom package.

ggplot() +
  geom_polygon(
    data = broom::tidy(districts, region = 'index'),
    aes(
      x = long,
      y = lat,
      group = group,
      fill = id
      ),
    color = 'grey',
    size = .5
  ) +
  coord_equal() +
  theme_minimal() + 
  theme(
    panel.grid.major = element_blank(), 
    panel.grid.minor = element_blank(), 
    axis.line = element_blank(), 
    axis.text.x = element_blank(), 
    axis.text.y = element_blank(),  
    axis.ticks = element_blank(), 
    axis.title.x = element_blank(),  
    axis.title.y = element_blank(),
    legend.position = 'bottom',
    legend.title = element_text(size = 20) , 
    legend.text = element_text(size = 10)
  )