Home > Software design >  Plotting Shapefile Aesthetics must be either length 1 or the same as data with fill
Plotting Shapefile Aesthetics must be either length 1 or the same as data with fill

Time:04-07

I am trying to plot a shapefile using its data as fill. When trying this, I, unfortunately, run into the error Aesthetics must be either length 1 or the same as the data (8112701): fill

My data is a 284 long SpatialPolygonsDataFrame, with the format

nations
  @data
    $OBJECTID (numeric)
    $CNTRY_NAME (chr)
    $CNTRY_CODE (chr)
    $BPL_CODE (chr)
    $deaths (numeric)
    $cases (numeric)
  @polygons
    list of all polygons

The code I am trying to use is:

ggplot()  
  geom_polygon(data=nations, aes(x=long,y=lat,group=group,fill=nations@data$cases))  
  theme_void()

The backtrace is

1. base `<fn>` (x)
2. ggplot2:::print.ggplot(x)
4. ggplot2:::ggplot_build.ggplot(x)
5. ggplot2 by)layer(function(l, d) l$compute_aesthetics(d, plot))
6. ggokit2 f(l= layers[[i]], d=date[[i]]])
7. l$compute_aestehetics(d, plot)
8. ggplot2 f(..., self=self)
9. ggplot2:::check_aesthetics(evaled, n)

Error in check_aesthetics(evaled, n)

CodePudding user response:

The problem is caused by using two different objects (the polygon and dataframe) within the same plotting command. Assigning separate colours (through fill) to a SpatialDataFrame in ggplot is tricky though. There are two approaches you might consider to solve your issue:

  1. Convert your SpatialDataFrame to a simple dataframe and add the cases manually, then plot using geom_polygon (see link).
  2. Load your spatial data as an SF object and plot through geom_sf (which is more flexible) (see link).

CodePudding user response:

I'd recommend converting this to an sf object. I don't know what your dataset is but here is an example that will convert an sp object to sf and then plot using ggplot2

library(sf)
#> Linking to GEOS 3.9.1, GDAL 3.2.3, PROJ 7.2.1
library(ggplot2)

world <- spData::world

# make into an spatialpolygonsdataframe
world_sp <- sf::as_Spatial(world)

world_sp |> 
  sf::st_as_sf() |> 
  ggplot(aes(fill = lifeExp))  
  geom_sf()

Created on 2022-04-06 by the reprex package (v2.0.1)

  • Related