rcolorsaesscalecontinuous

How to tell R to use wider range of colors for my geom point chart?


I am using geom_point to create R Chart. Below is the snippet of code I am using.

geom_point(aes(color=MyColumnHeading))

It all works. So far so good. The problem I am having is the following. The column MyColumnHeading, in the .CSV file, contains "continuous" numerical values. For example 99.5, 98.2, 96, 85.5, 60..so on and so forth. What I am trying to do is depict different numerical values using different colors on the chart, depending on the numerical value. That too works. Except the colors are all too close together or too similar. R, by default, is using a very narrow band out of the color spectrum. All around blue color, thus various shades of blue.

The various shades of blue colors are so similar that I cannot tell them apart. There is not enough contrast. If R were to use a wider range of colors from the color spectrum, I think it will work better. For example, high values could be red, others could be green, some blue, etc.

if I have discrete values in the column, instead of continuous numerical values, and I know the possible discrete values upfront, in order to have better control over the depicted colors, I have used the following R code

scale_colour_manual(values=c("ColValue1"="lightblue","ColValue2"="brown","ColValue3"="orange","ColValue4"="red"))

And it works. But in the current scenario, I do not really know all the continuous column values upfront, there are too many different ones.

Is there a way for me to specify to R to use a wider range of colors from the color spectrum? And solve my problem?

Or some other way so that I have a high contrast between depicted colors representing different continuous numerical values?

Thank you D


Solution

  • You can use scale_color_gradientn as Stefan suggests, though an easy method with a pleasant and widely divergent palette is to use scale_color_distiller

    p <- ggplot(df, aes(x, y)) +
      geom_point(aes(color = MyColumnHeader), size = 5) +
      theme_light(base_size = 16)
    
    p + scale_color_distiller(palette = "Spectral")
    

    enter image description here

    You could also use scale_color_viridis_c

    p + scale_color_viridis_c()
    

    enter image description here

    Both of these have the ability to select a range of different palettes, which you can find in their respective help files.


    Made-up data set

    set.seed(1)
    df <- data.frame(x = runif(100), y = runif(100),
                     MyColumnHeader = sample(100))