Skip to content

strange interaction of geom_raster and scale_{x,y}_continuous #3539

Closed
@paciorek

Description

@paciorek

If one applies scale_{x,y}_continuous to a raster plot but sets the x- or y-axis limits to be smaller than the extent of the data grid, the resulting plotting of the raster cells is distorted, with the cells shrunk in the dimension where the limit is set "too" small.

## Setup simple grid.
dat = expand.grid(x = seq(-2, 2, by = 1), y = seq(-2, 2, by = 1))
dat$val <- (1:nrow(dat))/nrow(dat)

## Case A: This plots fine without scale_{x,y}_continuous.
ggplot() + geom_raster(data = dat, aes(x = x, y = y, fill = val)) + geom_hline(yintercept = 0) + geom_vline(xintercept = 0)

## Case B: This plots fine too with limits set to be larger than extent of data grid.
ggplot() + geom_raster(data = dat, aes(x = x, y = y, fill = val)) + geom_hline(yintercept = 0) + geom_vline(xintercept = 0) + scale_x_continuous(limits = c(-3.5, 3.5)) + scale_y_continuous(limits = c(-3.5,3.5))

## Case C: y limits  are now more restricted than data limits and don't align with the data grid.
## Scaling in y direction is now distorted.
## Note that the center of the middle grid box should be at (0,0) where the horizontal and vertical lines intersect.
ggplot() + geom_raster(data = dat, aes(x = x, y = y, fill = val)) + geom_hline(yintercept = 0) + geom_vline(xintercept = 0) + scale_x_continuous(limits = c(-2.5, 2.5)) + scale_y_continuous(limits = c(-2,2.5))

Here's info on my setup:

> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Ubuntu 18.04.2 LTS

[...snip ...]

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_3.2.1    

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