stats_noob
stats_noob

Reputation: 5935

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

Thanks!

Upvotes: 0

Views: 606

Answers (1)

manro
manro

Reputation: 3677

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

Upvotes: 1

Related Questions