Manual scale for geom_raster

1,117 views
Skip to first unread message

Thiago V. dos Santos

unread,
Sep 18, 2014, 6:29:57 PM9/18/14
to ggp...@googlegroups.com
Hi all,

When plotting data with geom_raster, is there any way to create a "categorical" (rather than continuous) scale?

For example, I would like to specify colors, labels, breaks and title for the (randomly generated) data below:

# Generate data
pp <- function (n,r=4) {
 x <- seq(-r*pi, r*pi, len=n)
 df <- expand.grid(x=x, y=x)
 df$r <- sqrt(df$x^2 + df$y^2)
 df$z <- cos(df$r^2)*exp(-df$r/6)
 df
}

# justification
df <- expand.grid(x = 0:5, y = 0:5)
df$z <- runif(nrow(df))

# plot
ggplot (df) +
geom_raster (data=df, aes(x, y, fill = z)) 

 
Many thanks in advance,
--
Thiago V. dos Santos
PhD student
Land and Atmospheric Science
University of Minnesota
http://www.laas.umn.edu/CurrentStudents/MeettheStudents/ThiagodosSantos/index.htm
Phone: (612) 323 9898

Peter Goldstein

unread,
Sep 19, 2014, 7:18:46 AM9/19/14
to ggp...@googlegroups.com
Hi Thiago,
As with other geoms, you can use factor() in your geom_raster to get R to treat your z variable as categories. So it would be:
geom_raster(data=df, aes(x, y, fill = factor(z)))

Some things to note.

First, your random function is going to return continuous values, so they'll all be different with virtual certainty. I assume in your real implementation, you have data that more "naturally" inclines itself toward categories. If your data really are continuous, the gradient color probably is the best way to display them.

Second, when you're picking the manual colors you mentioned, bear in mind the levels in a factor are sorted alphabetically. This is how ggplot2 maps the vectors values and labels to your factor. So when assigning labels and colors (through scale_color_manual), it'll look like this:

df <- data.frame(x=1:20, y=1:20, z=c(rep('x',5), rep('z',5), rep('w',5), rep('a',5)))
ggplot() +
  geom_point(data=df, aes(x=x, y=y, color=z), shape=15,size=20) +
  scale_color_manual(values=c("red","brown","ivory","yellow"),
    labels=c("apples","walnuts","xylophones","zits"))

Hope this helps!
- Peter

--
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

---
You received this message because you are subscribed to the Google Groups "ggplot2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ggplot2+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ben Bond-Lamberty

unread,
Sep 19, 2014, 9:21:05 AM9/19/14
to ggp...@googlegroups.com
Might also check out the cut() function for putting continuous data
into categories.
Ben
Reply all
Reply to author
Forward
0 new messages