geom_raster with partial data

852 views
Skip to first unread message

Osmo Salomaa

unread,
Mar 22, 2012, 7:54:47 AM3/22/12
to ggp...@googlegroups.com
geom_raster seems to behave odd, when data is not a full rectangle. For example compare tiles and raster in the following

df = expand.grid(x=-10:10, y=-10:10)
df$z = rnorm(nrow(df))
df = subset(df, abs(x) + abs(y) > 15)
plot = (ggplot(df, aes(x, y))
        + geom_raster(aes(fill=z))
        + geom_tile(fill=NA, color="red", size=0.5)
        + coord_equal())

print(plot)

geom_raster seems to stretch the data to fill the gaps. Why? As a workaround I tried using NAs in the grid.

df = expand.grid(x=-10:10, y=-10:10)
df$z = rnorm(nrow(df))
df$z[abs(df$x) + abs(df$y) <= 15] = NA
plot = (ggplot(df, aes(x, y))
        + geom_raster(aes(fill=z))
        + coord_equal())

print(plot)

NAs are rendered with a grey color, but where is that color defined? I'd like to use white or alpha=0.

How do I use geom_raster with non rectangular or incomplete data?

Hadley Wickham

unread,
Mar 22, 2012, 8:58:37 AM3/22/12
to Osmo Salomaa, ggp...@googlegroups.com
On Thu, Mar 22, 2012 at 6:54 AM, Osmo Salomaa <osmo.s...@strafica.fi> wrote:
> geom_raster seems to behave odd, when data is not a full rectangle. For
> example compare tiles and raster in the following
>
> df = expand.grid(x=-10:10, y=-10:10)
> df$z = rnorm(nrow(df))
> df = subset(df, abs(x) + abs(y) > 15)
> plot = (ggplot(df, aes(x, y))
>         + geom_raster(aes(fill=z))
>         + geom_tile(fill=NA, color="red", size=0.5)
>         + coord_equal())
>
> print(plot)
>
> geom_raster seems to stretch the data to fill the gaps. Why?

Because that's the way rasters work - they have to fill up the total
space you give them. If you reduce the number of pixels, each pixel
gets bigger.

> As a workaround
> I tried using NAs in the grid.
>
> df = expand.grid(x=-10:10, y=-10:10)
> df$z = rnorm(nrow(df))
> df$z[abs(df$x) + abs(df$y) <= 15] = NA
> plot = (ggplot(df, aes(x, y))
>         + geom_raster(aes(fill=z))
>         + coord_equal())
>
> print(plot)
>
> NAs are rendered with a grey color, but where is that color defined? I'd
> like to use white or alpha=0.

Try

plot + scale_fill_gradient(na.value = NA)

Hadley

--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/

Osmo Salomaa

unread,
Mar 22, 2012, 9:12:15 AM3/22/12
to ggp...@googlegroups.com, Osmo Salomaa


On Thursday, March 22, 2012 2:58:37 PM UTC+2, Hadley Wickham wrote:

Because that's the way rasters work - they have to fill up the total
space you give them. If you reduce the number of pixels, each pixel
gets bigger.

OK. I think the documentation should clarify this. Currently it just implies geom_raster is similar in result, but more efficient than geom_tile.
 

plot + scale_fill_gradient(na.value = NA)

Thanks. That works.
Reply all
Reply to author
Forward
0 new messages