简体   繁体   中英

Plotly: how to specify symbol and color based on value?

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?

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))

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