繁体   English   中英

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

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

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

例如:

library(plotly)


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

如何将大于20的所有点都显示为黄色方块?

您可以执行以下操作:

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

是的,有可能,我会首先使用cut()plot_ly()之外进行所有分组和形状/颜色规范。 然后在引用新的颜色和形状变量时利用plot_ly()内部的文字I()语法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM