R 根据其他变量的值绘制标记/线条颜色

问题描述 投票:0回答:2

如何根据另一个变量的值绘制线条或标记。为了简单起见,我采用了这个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
r plotly colorbrewer
2个回答
0
投票

我们可以将

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


0
投票
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))

© www.soinside.com 2019 - 2024. All rights reserved.