Search code examples
rggplot2colorsgeomdot-plot

How change color after certain intervals in ggplot2?


I have following data:

dput(data)

I used following code to generate the plot:

p <- ggplot(data, aes(Zscore, ID))
p + geom_point(aes(colour=pval, size=Hit)) +
    scale_color_gradientn(colours=rainbow(4), limits=c(0, 1)) +
    geom_vline(xintercept=0, size=0.2, colour="blue", linetype="dotted") +
    theme(panel.background=element_rect(fill="gray95", colour="gray95"),
          panel.grid.major=element_line(size=0.1,linetype='solid', colour="gray90"), 
          panel.grid.minor=element_line(size=0.1,linetype='solid', colour="gray90"),
          axis.title.y=element_blank()) +
    expand_limits(x=c(-2,3)) +
    scale_x_continuous(breaks=c(-3,-2,-1,0,1,2,3)) +
    scale_y_discrete(limits=rev(data$ID))

Output in the output, I want to change the color (to green) of positive Zscore values. Also to increase the hit to 0,10,20,25,50....


Solution

  • The plot below is maybe not what is wanted.

    • To have the color change to green when the Z-score is positive means it should be mapped to Zscore, not to pval;
    • Also, the aesthetic size for lines was deprecated in ggplot2 3.4.0, I am using linewidth instead.
    library(ggplot2)
    
    p <- ggplot(data, aes(Zscore, ID))
    p + geom_point(aes(colour = Zscore > 0, size = Hit)) +
      scale_color_manual(
        name = 'Z-score',
        labels = c("Negative", "Positive"),
        values = c(`FALSE` = 'red', `TRUE` = 'green')
      ) +
      scale_size_continuous(breaks = c(0,10,20,25,50, 75, 100)) +
      geom_vline(xintercept=0, linewidth=0.2, colour="blue", linetype="dotted") +
      theme(panel.background=element_rect(fill="gray95", colour="gray95"),
            panel.grid.major=element_line(linewidth=0.1,linetype='solid', colour="gray90"), 
            panel.grid.minor=element_line(linewidth=0.1,linetype='solid', colour="gray90"),
            axis.title.y=element_blank()) +
      expand_limits(x=c(-2,3)) +
      # scale_x_continuous(breaks=c(-3,-2,-1,0,1,2,3, 4, 5, 6)) +
      scale_x_continuous(name = 'Z-score', breaks = pretty(data$Zscore)) +
      scale_y_discrete(limits=rev(data$ID))
    

    Created on 2022-11-18 with reprex v2.0.2