问题描述
在R中使用plotly
进行绘制时,如何根据值指定颜色和符号?例如,对于mtcars
示例数据集,如果mtcars$mpg
大于或小于18,如何将其绘制为红色正方形?
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?
例如:
library(plotly)
p <- plot_ly(type = "scatter", data = mtcars, x = rownames(mtcars), y = mtcars$mpg,
mode = "markers" )
如何将大于20的所有点都显示为黄色方块?
How to get all points above 20 as yellow squares?
推荐答案
您可以执行以下操作:
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/行和散点图/#mapping-data-to-symbols
是的,有可能,我会先使用cut()
在plot_ly()
之外进行所有分组和形状/颜色规范.然后在引用新的颜色和形状变量时利用plot_ly()
内的文字I()
语法:
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))
这篇关于密谋:如何根据值指定符号和颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!