简体   繁体   中英

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 (ie based on my_data$color) might not actually be colored with that color (eg 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!

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:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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