3

I am plotting x and y based on coordinates, the color is a third continuous variable with 6 decimals.

ggplot(data, aes(x=x, y=y, color=continuous_variable)) +
  geom_point()

Currently, the color is creating the gradient based on 3 decimals but I would like it to show 5.

Is there a way to increase the number of decimal places ggplot uses to create the gradient?

tjebo
  • 21,977
  • 7
  • 58
  • 94
  • 1
    Welcome to SO, nice first question! Just to clarify - just because it is *shown* does not mean ggplot uses those numbers for creating the gradient. The gradient will be created by the "breaks" that you pass to this function (or automatically). The labels are generated separately and then mapped to those breaks (which is alluded to in Roland's answer). In below answer, if you don't set the breaks explicitly, the underlying gradient calculation will still remain the same (and is likely to include even way more than 5 decimals). – tjebo Jan 13 '21 at 08:50
  • Check this thread, it is really important for all people who work with data and computers: [Why are these numbers not equal](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal) – tjebo Jan 13 '21 at 08:50
  • Thank you, this gave me something to think about! – Nina Maaranen Jan 14 '21 at 12:49

1 Answers1

5

You can pass a function that creates the labels from the breaks. Here I use sprintf to create character strings with the desired number (5) of decimals:

library(ggplot2)

ggplot(mtcars, aes(mpg, wt, colour = cyl)) + geom_point()+ 
  scale_color_gradient(labels = function(x) sprintf("%.5f", x))
zx8754
  • 52,746
  • 12
  • 114
  • 209
Roland
  • 127,288
  • 10
  • 191
  • 288