Home > Net >  ggplot - extract the values associated with breaks in a continuous colour scale
ggplot - extract the values associated with breaks in a continuous colour scale

Time:06-07

I would like to extract the breaks and the colour values associated with a ggplot continuous colour scale. There are multiple answers to finding the colour associated with each date point (like enter image description here

I would like to get a data frame showing breaks (12.5, 15, 17.5, 20) and the colour values associated with them.

Many thanks!

CodePudding user response:

There are two ways of doing this, once with building the plot and once without building the plot.

If we build the plot;

library(ggplot2)

df <- data.frame(x = 1:10, y = 1:10, col = 11:20)

ggplot(df)  
  geom_point(aes(x = x, y = y, colour = col))

We can extract the scale and use it to retrieve the relevant information.

# Using build plot
build <- ggplot_build(last_plot())

scale <- build$plot$scales$get_scales("colour")
breaks  <- scale$get_breaks()
colours <- scale$map(breaks)

data.frame(breaks = breaks, colours = colours)
#>   breaks colours
#> 1     NA  grey50
#> 2   12.5 #1D3F5E
#> 3   15.0 #2F638E
#> 4   17.5 #4289C1
#> 5   20.0 #56B1F7

Alternatively, we can skip building the plot and use the scales themselves directly, provided we 'train' the scales by showing it the limits of the data.

scale  <- scale_colour_continuous()
scale$train(range(df$col))
breaks  <- scale$get_breaks()
colours <- scale$map(breaks)

data.frame(breaks = breaks, colours = colours)

As you can see, the default breaks algorithm produces an out-of-bounds break. If you want to use the information later on, it might be good to filter those out.

  • Related