# [R] Choosing the number of colour breaks in ggplot2

hadley wickham h.wickham at gmail.com
Fri Jul 13 16:05:52 CEST 2007

```Hi Karl,

There's no official way to do it, but you can "hack" the colour
gradient scale to do what you want:

x=-10:10
y=-10:10
dat=expand.grid(x=x,y=y)
dat\$z=dat\$x^2+dat\$y^2-100

# Create a modified scale
gr <- scale_fill_gradient2()\$clone()
gr\$breaks <- function(.) seq(-100, 100, by=10)

ggplot(dat, mapping=aes(x=x, y=y, fill=z)) +
geom_tile() + gr

# Or to use the range of the scale if you don't want to set it by hand
gr\$breaks <- function(.) seq(.\$frange()[1], .\$frange()[2], length=10)

This works because ggplot2 is built on top of the proto library and
has mutable objects.  Most of the time you don't notice this because
the default functions operate with R's copy-on-modify semantics.

Hadley

On 7/13/07, Karl Ove Hufthammer <Karl.Hufthammer at math.uib.no> wrote:
> A seemingly simple problem has me stumped. Is it possible to choose the
> number of colour breaks for a gradient scale in the current version of
> ggplot2?
>
> Here is a simple example:
>
> ---------------------------------------------
> x=-10:10
> y=-10:10
> dat=expand.grid(x=x,y=y)
> dat\$z=dat\$x^2+dat\$y^2-100
>
> ggplot(dat, mapping=aes(x=x, y=y, fill=z)) +
>   geom_tile() + scale_fill_gradient2()
> ---------------------------------------------
>
> The image shows many (61) colours, but only 5 of them are shown in the
> legend. How do I change the legend to show, say, 10 colours?
>
>
> --
> Karl Ove Hufthammer
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

```

More information about the R-help mailing list