简体   繁体   English

ggplot - 提取与连续色标中的中断相关的值

[英]ggplot - extract the values associated with breaks in a continuous colour scale

I would like to extract the breaks and the colour values associated with a ggplot continuous colour scale.我想提取与 ggplot 连续色标相关的中断和颜色值。 There are multiple answers to finding the colour associated with each date point (like this ), which can also be used to get discrete scale values, but I haven't seen an approach for a continuous colour scale.找到与每个日期点关联的颜色有多种答案(像这样),它也可以用来获取离散的比例值,但我还没有看到连续颜色比例的方法。 I don't want to force the scales, just retrieve the values that ggplot generates.我不想强制使用比例,只需检索 ggplot 生成的值。

example:例子:

library(ggplot)
df <- data.frame(x = 1:10, y = 1:10, col = 11:20)
ggplot(df) +
  geom_point(aes(x = x, y = y, colour = col))

在此处输入图像描述

I would like to get a data frame showing breaks (12.5, 15, 17.5, 20) and the colour values associated with them.我想获得一个显示中断(12.5、15、17.5、20)和与它们相关的颜色值的数据框。

Many thanks!非常感谢!

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.如果您想稍后使用这些信息,最好将其过滤掉。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM