Closed ASeatonSpatial closed 2 years ago
Ah just noticed that this will give an error if there is no data slot. Adding a check e.g. via inherits(data, "SpatialPolygonsDataFrame")
would solve that.
Yes, ggplot2::fortify
appears to mostly exist for backward compatibility. I notice that in gg.SpatialPixelsDataFrame
we use as.data.frame()
instead. The main trick is to keep track of the coordinate names, which ggplot2::fortify
breaks, leading to the various extra code in the gg functions to get around that. Looking at the code from ggplot2:::fortify.SpatialPolygonsDataFrame
, it's not clear what it even tries to do with the data part. It does start with as.data.frame()
, but then by default doesn't use the result, which I'd argue is a bug in fortify
. The fortify
documentation points to broom
, that points to broom::tidy
and broom::sp_tidiers
, which will be deprecated in favour of sf::st_as_sf
. We may need some transition helpers of our own before fully adding sf
support.
But the broom:::tidy.SpatialPolygonsDataFrame
code may have the same issue as fortify
.
The missing data slot is more to do with not having a gg.SpatialPolygonsDataFrame
. A bit odd that.
The piece
index is an index within each polygon. The appropriate join-variable is id
:
df <- ggplot2::fortify(data)
if (inherits(data, "SpatialPolygonsDataFrame")) {
data[["id"]] <- unique(df[["id"]])
df <- dplyr::left_join(df, as.data.frame(data), by = "id")
}
I'll also change the default alpha value from 0.1 to 0.2; perhaps the default should be 1.
library(INLA)
#> Loading required package: Matrix
#> Loading required package: foreach
#> Loading required package: parallel
#> Loading required package: sp
#> This is INLA_99.99.9999 built 2022-01-11 19:37:35 UTC.
#> - See www.r-inla.org/contact-us for how to get help.
#> - To enable PARDISO sparse library; see inla.pardiso()
library(inlabru)
library(ggplot2)
library(patchwork)
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(SpatialEpi) # contains scotland Lip cancer data
# load data
data(scotland)
lip_data = scotland$spatial.polygon
lip_data$cases = scotland$data$cases
ggplot() +
gg(lip_data, aes(fill = cases), alpha=1) +
coord_equal() +
theme_minimal()
#> Regions defined for each Polygons
Created on 2022-01-11 by the reprex package (v2.0.1)
I wanted to plot a polygon object and set
aes(fill = covariate_name)
wherecovariate_name
is a covariate in aSpatialPolygonsDataFrame
.However this does not work:
This seems to be caused by fortify which doesn't store the information in the data slot of the
SpatialPolygonsDataFrame
.This change to
gg.SpatialPolygons
appears to fix the issue:Created on 2022-01-11 by the reprex package (v2.0.1)