Search code examples
rggplot2bar-chartgradientfill

Set specific values for scale_fill_distiller


I'm realising different barplots to analyse the expression of different genes. What I would like to do is to put the same y scale for every gene (in my case 0-100).

I would also like to set in ggplot a scale fill that allow me to put as maximum 100 and 0 as minimum for each gene.

I give you some data so you can try some scripts:

Stages  TPH
00  9.96255848
04  9.778249598
08  10.01361333
12  28.5846484
16  66.26588384
20  41.51936636
24  30.02374287
28  24.32832801
32  23.88064848
36  23.20842877
40  21.95980567
44  25.21053631
48  24.98618594
52  22.19588764
72  20.17286473

Here there is an example of barplot I would like to have but which has as maximum the values of TPH: enter image description here

Thank you in advance for your help!

Cheers, Beatrice

I tried whith ggplot and scale_fill_distiller but didn't manage to put the scale I wanted.


Solution

  • If I understand it correctly, you want both the y-axis and the color scale for the fill of the bars to range from 0 to 100. This can be achieved by using ylim() and the limits argument for scale_fill_distiller():

    # load libraries
    library(ggplot2)
    
    # assign your data to the variable dat
    dat <- structure(list(Stages = c("00", "04", "08", "12", "16", "20", 
                                     "24", "28", "32", "36", "40", "44",
                                     "48", "52", "72"),
                          TPH = c(9.96255848, 9.778249598, 10.01361333,
                                  28.5846484, 66.26588384, 41.51936636,
                                  30.02374287, 24.32832801, 23.88064848,
                                  23.20842877, 21.95980567,25.21053631,
                                  24.98618594, 22.19588764, 20.17286473)),
                     row.names = c(NA, 15L),
                     class = "data.frame")
    
    # plot
    ggplot(dat, aes(x = Stages, y = TPH)) +
      geom_col(aes(fill = TPH)) +
      ylim(limits = c(0, 100)) +
      scale_fill_distiller(palette = "RdYlBu",
                           limits = c(0, 100))
    

    Output: enter image description here

    Please consider that the information encoded by the y-axis and by the color scale is redundant, which is usually not considered best practice.