Is there a way to specify to the plot_ly()
function which values should appear as what symbol/color in a plot? For example, the mtcars
dataset, display mtcars$mpg < 18
as black x’s, mtcars$mpg > 19 && mtcars$mpg <25
as orange squares, and mtcars$mpg > 26
as red circles? I feel like this is a pretty general problem and have not been able to find any help anywhere.
Hey @kyleweise
There are lots of ways you could do this, but following what you have written:
p <- plot_ly() %>%
add_markers(x = which(mtcars$mpg < 18), y = mtcars$mpg[mtcars$mpg < 18], marker = list(color = 'black', symbol = 'cross')) %>%
add_markers(x = which(mtcars$mpg > 19 & mtcars$mpg < 25), y = mtcars$mpg[mtcars$mpg > 19 & mtcars$mpg <25], marker = list(color = 'orange', symbol = 'square')) %>%
add_markers(x = which(mtcars$mpg > 26), y = mtcars$mpg[mtcars$mpg > 26], marker = list(color = 'red', symbol = 'circle'))
1 Like
This is perfect! Sorry for the late response. But this is exactly what I needed.
Hey @bcd
For my own dataset, each of these conditions might not always be met (i.e. in mtcars
, there might not be any rows where mpg
is between 19 and 25). So when I run this code for my own dataset, I get an error saying:
“Error: Must supply x
and y
attributes”
Because the middle add_markers()
's x
and y
have no value. Is there a way around this? So that it wouldn’t plot anything, and toggling the label in the legend won’t do anything to the plot.