Skip to content

Different behaviour of scales param na.value = NA in geom_tile() and geom_raster() #5523

@dieghernan

Description

@dieghernan

HI:

Following an issue on tidyterra (dieghernan/tidyterra#120, see also https://stackoverflow.com/questions/77474839/ggplot-of-raster-maps-horizontal-vertical-grid-cells-distortion/77486091#77486091) I think the root cause may be on how ggplot2 handles the param na.value = NA on geom_raster() (note that geom_spatraster() is leveraging on this ggplot2 function). See the different behaviour compared with geom_tile():

ex <- tibble::tribble(
  ~x, ~y, ~ExampleMap2,
  4415000L, 2865000L, 1L,
  4425000L, 2865000L, NA,
  4435000L, 2865000L, NA,
  4445000L, 2865000L, NA,
  4415000L, 2855000L, NA,
  4425000L, 2855000L, NA,
  4435000L, 2855000L, NA,
  4445000L, 2855000L, NA,
  4415000L, 2845000L, 1L,
  4425000L, 2845000L, NA,
  4435000L, 2845000L, NA,
  4445000L, 2845000L, NA,
  4415000L, 2835000L, NA,
  4425000L, 2835000L, NA,
  4435000L, 2835000L, NA,
  4445000L, 2835000L, NA,
  4415000L, 2825000L, 1L,
  4425000L, 2825000L, NA,
  4435000L, 2825000L, NA,
  4445000L, 2825000L, 1L
)

library(ggplot2)

p_raster <- ggplot(ex, aes(x, y)) +
  geom_raster(aes(fill = ExampleMap2)) +
  coord_equal()

# As expected
p_raster

# With na.value = NA extra cells are filled
p_raster +
  scale_fill_viridis_c(na.value = NA)
#> Warning: Removed 16 rows containing missing values (`geom_raster()`).

# Not happening with geom_tile
ggplot(ex, aes(x, y)) +
  geom_tile(aes(fill = ExampleMap2)) +
  coord_equal() +
  scale_fill_viridis_c(na.value = NA)

Created on 2023-11-15 with reprex v2.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions