Mikkel Astrup
Mikkel Astrup

Reputation: 415

GGplot scatterplot color interval

Im currently getting back into using R, but its been a while so im a little rusty.

I have the following code for making plots using ggplot2:

ggplot(NewData, aes(x=PAH16Cons ,y=Depth, group(FileName)))+
                geom_point(aes(colour=PAH16Cons))+
                scale_y_continuous(trans="reverse")+
                facet_wrap(facets = vars(FileName))+
                scale_color_gradient2("Cons mg/kg ts", 
                                      breaks =c(0,100,500),
                                      low = 'green',
                                      mid = 'yellow',
                                      high = 'red')

Im trying to change the color of the plot so values between 0-100 are green, 100-500 yellow and above 500 red. enter image description here

But, as you can see I get no green, any help would be greatly appreciated

Upvotes: 1

Views: 547

Answers (1)

LC-datascientist
LC-datascientist

Reputation: 2096

If you want to use one color shade for each range of values, you can create a grouping (factor) column with levels on the condition of PAH16Cons values <100, 100-500, or >500. Afterwards, use this column for the color aesthetics in the ggplot and use scale_color_manual(values=c("green", "yellow", "red")) to customize the color.

NewData$cols <- with(NewData, 
    factor(
        ifelse(PAH16Cons < 100, "<100", 
            ifelse(PAH16Cons >= 100 & PAH16Cons <= 500, "100-500", ">500")), 
        levels = c("<100", "100-500", ">500")))

ggplot(NewData, aes(x=PAH16Cons ,y=Depth, group(FileName)))+
    geom_point(aes(colour=cols))+
    scale_y_continuous(trans="reverse")+
    facet_wrap(facets = vars(FileName))+
    scale_color_manual("Cons mg/kg ts", values=c("green", "yellow", "red"))

Run ?scale_color_manual for more information and examples.

Upvotes: 2

Related Questions