如何使用R中的Plotly软件包进行按两个因素分组的三维折线图



我已经查看了Plotly的官方网页,但我仍然无法绘制以下任务:

id <- c(rep(1,5), rep(2,5), rep(3,5), rep(4,5))
t <- rep(seq(50,75,length.out=5), 4)
x <- runif(20) + sin(t) 
y <- rnorm(20) + cos(t)
gender <- c(rep("F",10), rep("M",10))
smoke <- c(rep("Y",5), rep("N",10), rep("Y",5))
DATA <- data.frame(ID, t, x, y, gender, smoke)
fig <- plot_ly(DATA, x = ~t, y = ~y, z = ~x, .......)

假设我有4组患者(按2个因素分组,女性/男性和吸烟者/非吸烟者(,每个患者都与时间戳$t_I$上的5个观察值$(x_I,y_I($相关。因此,我需要为每个患者绘制一个三维折线图$${(t_I,x_I,y_I(}_{I=1}^{I=5}$,但所有这些都在一个绘图画布中。如果我想用红/蓝表示性别,用实线表示吸烟者,用虚线表示非吸烟者,并在图例中指定这些性别,我应该怎么做(最好使用R(?

你心目中的3D绘图可以这样实现:

library(plotly)
id <- c(rep(1,5), rep(2,5), rep(3,5), rep(4,5))
t <- rep(seq(50,75,length.out=5), 4)
x <- runif(20) + sin(t) 
y <- rnorm(20) + cos(t)
gender <- c(rep("F",10), rep("M",10))
smoke <- c(rep("Y",5), rep("N",10), rep("Y",5))
DATA <- data.frame(id, t, x, y, gender, smoke)
col_gender <- c(M = "red", F = "blue")
lt_smoke <- c(Y = "solid", N = "dash")
sym_id <- c(`1` = "circle", `2` = "square", `3` = "diamond", `4` = "cross")
fig <- plot_ly(DATA, 
x = ~x, y = ~y, z = ~t, symbol = ~id, color = ~gender, linetype = ~smoke, type = 'scatter3d', mode = 'lines+markers',
line = list(width = 6),
marker = list(size = 3.5, cmin = -20, cmax = 50),
colors = col_gender,
linetypes = lt_smoke,
symbols = sym_id)
fig

编辑:

在患者较多的情况下,最好的选择是使用变换groupby通过idid映射到颜色和附加组上

library(plotly)
id <- c(rep(1,5), rep(2,5), rep(3,5), rep(4,5), rep(5,5), rep(6,5), rep(7,5), rep(8,5))
t <- rep(seq(50,75,length.out=5), 8)
x <- runif(40) + sin(t) 
y <- rnorm(40) + cos(t)
gender <- c(rep("F",10), rep("M",10), rep("F",10), rep("M",10))
smoke <- c(rep("Y",5), rep("N",10), rep("Y",5), rep("Y",5), rep("N",10), rep("Y",5))
lt_smoke <- c(Y = "solid", N = "dash")
sym_id <- c(M = "circle", F = "square")
fig <- plot_ly(DATA, 
x = ~x, y = ~y, z = ~t, symbol = ~gender, color = ~id, linetype = ~smoke, type = 'scatter3d', mode = 'lines+markers',
line = list(width = 6),
marker = list(size = 3.5, cmin = -20, cmax = 50),
linetypes = lt_smoke,
symbols = sym_id,
transforms = list(
list(
type = 'groupby',
groups = ~id)
))
fig

相关内容

  • 没有找到相关文章

最新更新