4

When plotting with plotly in R, how does one specify a color and a symbol based on a value? For example with the mtcars example dataset, how to plot as a red square if mtcars$mpg is greater or less than 18?

For example:

library(plotly)


p <- plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
             mode = "markers" )

How to get all points above 20 as yellow squares?

Kyle Weise
  • 869
  • 1
  • 8
  • 29
  • Please post the code you have tried so far. SO is ready to help, but please see the community guidelines for posting https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Nate Jul 07 '17 at 14:45
  • @NateDay See updated question – Kyle Weise Jul 07 '17 at 14:50

1 Answers1

7

you could do something like this:

plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
        mode = "markers", symbol = ~mpg > 20, symbols = c(16,15),
        color = ~mpg > 20, colors = c("blue", "yellow"))

https://plot.ly/r/line-and-scatter/#mapping-data-to-symbols

yes it's possible, I'd make all of your grouping and shape/color specification outside of plot_ly() with cut() first. And then take advantage of the literal I() syntax inside of plot_ly() when referencing your new color and shape vars:

data(mtcars)

mtcars$shape <- cut(mtcars$mpg,
                    breaks = c(0,18, 26, 100),
                    labels = c("square", "circle", "diamond"))
mtcars$color <- cut(mtcars$mpg,
                    breaks = c(0,18, 26, 100),
                    labels = c("red", "yellow", "green"))

plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
        mode = "markers", symbol = ~I(shape), color = ~I(color))
Nate
  • 10,361
  • 3
  • 33
  • 40
  • Awesome! Can this be extended to include more? i.e. mpg 0-18 is red squares, mpg 19-25 is yellow circles, mpg 26+ is green diamonds? If so how would this look in the code? – Kyle Weise Jul 07 '17 at 15:02
  • is that possible..? – Kyle Weise Jul 07 '17 at 15:30
  • 8
    anything is possible, but sometimes my bill paying job gets in the way of SO – Nate Jul 07 '17 at 15:50
  • I just tried this with my own example, where the `breaks` would have to be much smaller numbers(0.01. 0.05), and it doesn't seem to work. Check out another question of mine [here](https://stackoverflow.com/questions/44971581/r-abline-equivalent-in-plotly) if you'd like to help – Kyle Weise Jul 07 '17 at 17:02