Bangyou
Bangyou

Reputation: 9816

How to specific colour for a continuous variable in ggplot2?

I want to manually set the colour for a continuous in ggplot2. How could I do this?

This is my example code.

library(ggplot2)
set.seed(1)
df <- data.frame(x = runif(100), y = runif(100), z = runif(100))

library(RColorBrewer)
cols <- rev(brewer.pal(11, 'RdYlBu'))

ggplot(df) + 
    geom_point(aes(x, y, colour = z)) +
    scale_colour_manual(values = cols)

Thanks for any suggestions.

Upvotes: 1

Views: 5082

Answers (1)

BBrill
BBrill

Reputation: 1942

This will work:

 library(ggplot2)
    set.seed(1)
    df <- data.frame(x = runif(100), y = runif(100), z = runif(100))

    library(RColorBrewer)
    cols <- rev(brewer.pal(11, 'RdYlBu'))

    ggplot(df, aes(x, y, colour = z)) + 
        geom_point()+
        scale_colour_gradientn(colours = cols)

Upvotes: 4

Related Questions