Search code examples
rplotlydata-visualization

Correctly Specifying Colors in Plotly


I am looking at this tutorial over here : https://plotly.com/r/line-and-scatter/

I tried to make a scatter plot in plotly (in R). The data I am using looks something like this:

library(plotly)

var1 = rnorm(100,100,100)
var2 = rnorm(100,100, 100)
my_data = data.frame(var1, var2)

my_data$color = ifelse(my_data$var1 > 0 & my_data$var1 < 50, "red", ifelse(my_data$var1>=50 & my_data$var1<100, "green", "yellow"))

Based on the tutorial, I then tried to color the points:

pal <- c("red", "green", "yellow")
pal <- setNames(pal, c("red", "green", "yellow"))

fig <- plot_ly(data = my_data, x = ~var1, y = ~var2, color = ~color, colors = pal)

fig
  • Is there a way to directly specify these colors without using the "pal" statement and directly specifying the colors from the data frame itself? I am worried that a point that "should" be colored a certain color (i.e. based on my_data$color) might not actually be colored with that color (e.g. a point that I wanted colored "red" is actually colored "green").

  • Is there a standard reference that can be used to specify colors? For example, the yellow color is too bright and difficult to read. I found this website that allows you to convert colors to their hexadecimal format (https://www.rapidtables.com/convert/color/rgb-to-hex.html), and this website that contains popular choices of colors in R (http://www.stat.columbia.edu/~tzheng/files/Rcolor.pdf). Can such inputs be used for specifying colors in plotly?

Thanks!


Solution

  • If I fully understand the question, then you can try this solution:

    Code:

    library(plotly)
    
    my_data <- data.frame(var1 = rnorm(100, 100, 100),
                          var2 = rnorm(100, 100, 100))
    
    my_data$color <- ifelse(my_data$var1 > 0 & my_data$var1 < 50, "red", 
                            ifelse(my_data$var1>=50 & my_data$var1<100, "green", "yellow"))
    
    fig <- plot_ly(data = my_data, x = ~var1, y = ~var2, color = ~color, colors = c("#228B22", "#FF4500", "#CCCC00"))
    
    fig
    

    Output:

    enter image description here