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

标签 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" )

如何将所有高于 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

是的,这是可能的,我会在 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))

关于r - Plotly:如何根据值指定符号和颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44973625/

相关文章:

python - plotly - 在 Plot.JS 中使用 graph_objects.Figure 轨迹

python - Pandas:使用plotly作为后端时如何选择绘图元素颜色?

python - key 错误: 'plotly_domain'

r - 如何改变 R ggplot 中 geom_text 中文本的长度?

r - R控制台左侧的 “+”符号是什么意思?

r - 如何在换行悬停标签上添加换行符

r - 在 Shiny 的应用程序上,ggplotly() 渲染的大小是 plot_ly() 的一半。如何解决?

r - 从 R 中的数字和停用词中过滤文本(不适用于 tdm)

r - 如何在R中删除具有相同值的列

c++ - 在 rcpp 中将列表转换为矩阵