Colorize Scatterplot with upper and lower limits

233 views Asked by At

I want to plot a scatterplot with an upper (0.40) and a lower (0.32) limit. I want to colorize the values between both limits in black, the values beneath the lower limit in blue and the values above the upper limit in red.

Here is my code, where I colorized the three different periods:

d_ply(Q, .(Actor), function(p){
  ggplot(p, aes(x = Date, y = BACE, colour=Period))+
  geom_point(shape=15)+scale_colour_manual(values=c("#000000", "#CC0000", "#0066FF"))+
  ylim(0,0.6)+
  geom_hline(yintercept=0.32, linetype="dotdash")+
  geom_hline(yintercept=0.40, linetype="dotdash")+
  theme(legend.position = "none", panel.background = element_rect(fill = "#FFFFFF",  colour="#000000"), panel.grid.major = element_line(colour = "grey", linetype = "dotted")) +
  facet_grid(.~ Period, scales="free", space="free")+
  ggtitle(unique(p$Actor))+
  ggsave(file = paste0("lta_",unique(p$Actor),"_BACE", ".pdf"))
})

Here is the dataset:

Date    Actor   BACE    Period
 1Q1    Ar  0,3448  P1
 1Q2    Ar  0,3096  P1
 1Q3    Ar  0,2771  P2
 1Q4    Ar  0,2412  P2
 2Q1    Ar  0,3291  P2
 2Q2    Ar  0,1575  P2
 2Q3    Ar  0,3072  P2
 2Q4    Ar  0,3252  P2
 3Q1    Ar  0,3138  P2
 3Q2    Ar  0,3241  P3
 3Q3    Ar  0,2867  P3
 3Q4    Ar  0,2587  P3
 4Q1    Ar  0,2983  P3
 4Q2    Ar  0,2933  P3
 4Q3    Ar  0,237   P3
 4Q4    Ar  0,2788  P3
 1Q1    Bu  0,3977  P1
 1Q2    Bu  0,3844  P1
 1Q3    Bu  0,3642  P2
 1Q4    Bu  0,3744  P2
 2Q1    Bu  0,3695  P2
 2Q2    Bu  0,3451  P2
 2Q3    Bu  0,3466  P2
 2Q4    Bu  0,3395  P2
 3Q1    Bu  0,3738  P2
 3Q2    Bu  0,3701  P3
 3Q3    Bu  0,3736  P3
 3Q4    Bu  0,3435  P3
 4Q1    Bu  0,3559  P3
 4Q2    Bu  0,3695  P3
 4Q3    Bu  0,4223  P3
 4Q4    Bu  0,4538  P3

Has anyone an idea how to colorize the limits instead of the periods?

Thank you!

1

There are 1 answers

1
shadow On BEST ANSWER

It's probably easiest to just create a new variable limit in your data, where you save the necessary factors. Then you can just change the function to color=limit.

Q[, "limit"] <- factor("below", levels=c("below", "between", "above"))
Q[Q[, "BACE"]>=0.32, "limit"] <- "between"
Q[Q[, "BACE"]>=0.4, "limit"] <- "above"

Then you just have to change the color=limit and the scale_colour_manual to

scale_colour_manual(values=c(between="#000000", above="#CC0000", below="#0066FF")) 

EDIT: If you have missing values in the BACEvariable, you can change the code to the following:

Q[!is.na(Q[, "BACE"]), "limit"] <- factor("below", 
                                          levels=c("below", "between", "above"))
Q[which(Q[, "BACE"]>=0.32), "limit"] <- "between"
Q[which(Q[, "BACE"]>=0.4), "limit"] <- "above"