【问题标题】:Convert an vector to a specific color for `plot()`将向量转换为 `plot()` 的特定颜色
【发布时间】:2022-08-20 16:22:40
【问题描述】:

下面是一个最小的工作示例。

library(ggplot2)

set.seed(926)
df <- data.frame(x. = rnorm(100),
                 y. = rnorm(100),
                 color. = rnorm(100))

library(ggplot2)
p <- ggplot(df, aes(x = x., y = y., color = color.)) + 
  geom_point() + 
  viridis::scale_color_viridis(option = \"C\")
p

p_build <- ggplot_build(p)

# The desired vector is below somehow I feel there must have an easier way to get it

p_build[[\"data\"]][[1]][[\"colour\"]]

df$color_converted <- p_build[[\"data\"]][[1]][[\"colour\"]]

具体来说,我喜欢使用viridis::viridis(option = \"C\") 配色方案。有人可以帮忙吗?谢谢。

*调整*

抱歉,我的问题不够清楚。这么说吧,在我的具体项目中,我无法使用ggplot2 包,不得不使用R 附带的纯plot() 函数。

我的目标是尝试使用基本 R 包重现上述情节。

plot(df$x., df$y., color = df$color_converted)

如果可能的话,谁能指导我如何自定义类似于ggplot2 的渐变图例,以legend() 为基础?

  • 很抱歉,但我无法真正按照您的意愿行事。您想用特定颜色更改点吗?
  • 本质上,我正在尝试将df 中的color. 向量转换为与scale_color_viridis(option = \"C\") 匹配,输出精确的十六进制颜色。

标签: r ggplot2 plot colors legend


【解决方案1】:

首先,您可以将颜色分配给名为“color2”的向量,并使用scale_colour_gradientn 将这些颜色分配给您的绘图。问题是颜色没有正确排序,所以你必须首先使用TSP 包来做到这一点。在下面的输出中,您可以看到您可以在不使用 scale_color_viridis 的情况下重新创建绘图:

set.seed(926)
df <- data.frame(x. = rnorm(100),
                 y. = rnorm(100),
                 color. = rnorm(100))

library(ggplot2)
library(TSP)
p <- ggplot(df, aes(x = x., y = y., color = color.)) + 
  geom_point() + 
  viridis::scale_color_viridis(option = "C")
p


p_build <- ggplot_build(p)

# The desired vector is below somehow I feel there must have an easier way to get it
color2 <- p_build[["data"]][[1]][["colour"]]

rgb <- col2rgb(color2)
lab <- convertColor(t(rgb), 'sRGB', 'Lab')
ordered_cols2 <- color2[order(lab[, 'L'])]

ggplot(df, aes(x = x., y = y.)) + 
  geom_point(aes(colour = color.)) +
  scale_colour_gradientn(colours = ordered_cols2, guide = "colourbar")

  #viridis::scale_color_viridis(option = "C")

创建于 2022-08-17,reprex v2.0.2

基数

您可以使用以下代码:

color2 <- p_build[["data"]][[1]][["colour"]]

rgb <- col2rgb(color2)
lab <- convertColor(t(rgb), 'sRGB', 'Lab')
ordered_cols2 <- color2[order(lab[, 'L'])]

layout(matrix(1:2,ncol=2), width = c(2,1),height = c(1,1))
plot(df$x., df$y., col = df$color_converted)

legend_image <- as.raster(matrix(ordered_cols2, ncol=1))
plot(c(0,2),c(0,1),type = 'n', axes = F,xlab = '', ylab = '', main = 'legend title')
text(x=1.5, y = seq(0,1,l=5), labels = seq(-3,3,l=5))
rasterImage(legend_image, 0, 0, 1,1)

输出:

【讨论】:

  • 感谢您对订购的深刻见解。我觉得我的问题不够清楚,有兴趣的请参考修改后的版本。非常感谢。
  • 嗨@yuw444,我添加了一些代码来重新创建base R 中的情节!
猜你喜欢
  • 2014-09-30
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
相关资源
最近更新 更多