如何根据另一个变量的值绘制线条或标记。为了简单起见,我采用了这个example.
所以我想根据 z 的值给 x 上色。实际上,最好使用我自己的自定义色谱。
library(plotly)
library(RColorBrewer)
df <- data.frame(x <- seq(from = -2, to = 2, b = 0.1),
y <- sin(x),
z <- runif(41)
)
p11 <- plot_ly() %>%
add_trace(type = "scatter",
x = ~x,
y = ~y,
mode = "markers",
marker = list(size = 10,
color = colorRampPalette(brewer.pal(10,"Spectral"))(41))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
p11
我们可以将
color
函数的add_trace()
参数设置为~z
color = ~z
library(plotly)
library(RColorBrewer)
plot_ly() %>%
add_trace(type = "scatter",
x = ~x,
y = ~y,
mode = "markers",
marker = list(size = 10,
color = ~z,
colors = colorRampPalette(brewer.pal(10, "Spectral"))(n = 41))) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis"),
yaxis = list(title = "y-axis"))
library(plotly)
library(RColorBrewer)
set.seed(101)
df <- data.frame(x <- seq(from = -2, to = 2, b = 0.1),
y <- sin(x),
z <- runif(41)
)
plot_ly(colors = colorRampPalette(brewer.pal(10,"Spectral"))(41)) %>%
add_trace(type = "scatter",
x = ~x,
y = ~y,
color = ~z,
mode = "markers",
marker = list(size = 10)) %>%
layout(title = "Multicolored sine curve",
xaxis = list(title = "x-axis", showgrid = FALSE),
yaxis = list(title = "y-axis", showgrid = FALSE))