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

Kyl*_*ise 4 r plotly

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

例如:

library(plotly)


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

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

Nat*_*ate 7

你可以做这样的事情:

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"))
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

  • 一切皆有可能,但有时我的账单支付工作会妨碍到 SO (8认同)