yuw444
yuw444

Reputation: 426

Convert an vector to a specific color for `plot()`

Below is a minimal working example.

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"]]

Specifically, I like to use viridis::viridis(option = "C") color scheme. Could anyone help with this? Thanks.

*Modify*

Sorry, my question wasn't clear enough. Let me put it this way, I couldn't utilize ggplot2 package and had to use the pure plot() function that comes with R, in my specific project.

My goal is to try to reproduce the above plot with the base R package.

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

If possible, could anyone also direct me on how to customize a gradient legend that is similar to ggplot2, with base legend()?

Upvotes: 1

Views: 177

Answers (1)

Quinten
Quinten

Reputation: 41225

First of all you can assign the colors to a vector called "color2" and use scale_colour_gradientn to assign these colors to your plot. The problem is that the colors are not sorted right so you have to do that first by using the TSP package. In the output below you can see that you can recreate the plot without using 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")

Created on 2022-08-17 with reprex v2.0.2

Base r

You can use the following code:

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)

Output:

enter image description here

Upvotes: 1

Related Questions