Plotly:如何根据值指定符号和颜色?

时间:2017-07-07 14:42:40

标签: r plotly

在R中使用plotly进行绘图时,如何根据值指定颜色和符号?例如,对于mtcars示例数据集,如果mtcars$mpg大于或小于18,如何绘制为红色方块?

例如:

library(plotly)


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

如何将所有高于20的点作为黄色方块?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

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

是的,我可以先使用plot_ly()cut()之外制作所有分组和形状/颜色规格。然后在引用您的新颜色和形状变量时利用I()内的文字plot_ly()语法:

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