Retrieve Colour - Value Mapping From ggplot

2020-03-30 16:04发布

问题:

I assume the ggplot scales creates some sort of function which reads the appropriate aes value and returns the colour, size, etc. Can this be used as a standalone function?

For example, to this function I will pass the necessary arguments (range, limits, high, low, etc.) and a value which I want to get the mapping for, and the output of the function will be the colour / size / etc.

# example of usage
HypotheticalScaleFunction(
   range = c(0,10),
   high = '#000000',
   low = '#222222',
   ValueToLookup = 5
)
# this should return -
"#111111"

回答1:

You can find this by reading through the source, by typing in scale functions. For example, if you read through the source for ggplot2::scale_color_continuous, you will find that it uses seq_gradient_pal from the scales package.

So, for color on a continious scale, we can define the following function (with the defaults that ggplot uses):

ColorScaleFunction <- function(Range, high = "#56B1F7", low = "#132B43", ValueToLookup) {
  seq_gradient_pal(low, high)((ValueToLookup - Range[1]) / diff(Range))
}

This results in the typical dark blue colors that you get by default, in heatmaps for example.

It produces #161616 on your example though.



标签: r ggplot2