4
votes

I have a dataframe with columns X , Y , VALUE. I am using ggplot2 to plot the values at the specified coordinates. But I wish to fill colour based on custom ranges for the VALUE column. For example :

VALUE    COLOUR
0 to 2    blue
2 to 5    green
5 to 10   red
10 to 20  yellow
20 to 30  orange
30 to 40  grey
>40       black

How do I fill specific colour for particular values using ggplot2 ?

I can resample my data if required and map individual resampled value to colours after that, for example :

VALUE    RESAMPLED VALUE    COLOUR
0 to 2        10             blue
2 to 5        20             green
5 to 10       30             red
10 to 20      40             yellow
20 to 30      50             orange
30 to 40      60             grey
>40           70             black

But the values are not getting mapped to colours with this code :

ggplot2::ggplot() + ggmap::theme_nothing() +
ggplot2::geom_tile(data = xyDataFrame, alpha = 0.6, aes(x = X, y = Y, fill=VALUE)) + 
ggplot2::scale_fill_gradientn(colours = c("blue", "green", "red", "yellow", "orange", "grey", "black"))
1

1 Answers

5
votes

You should probably use cut to make an additional variable in your data frame.

DATA$COLOUR <- cut(DATA$VALUE, c(0, 2, 5, 10, 20, 30, 40, Inf),
    c("blue", "green", "red", "yellow", "orange", "grey", "black"))