R:将 Plotly 图堆叠在彼此之上
Posted
技术标签:
【中文标题】R:将 Plotly 图堆叠在彼此之上【英文标题】:R: Stacking Plotly Graphs on Top of Each Other 【发布时间】:2021-10-02 23:25:12 【问题描述】:我正在使用 R。我正在尝试将多个 3D 表面以图形方式堆叠在一起,如下所示:
#functional code copied from the official plotly R website (https://plotly.com/r/3d-surface-plots/)
library(plotly)
z <- c(
c(8.83,8.89,8.81,8.87,8.9,8.87),
c(8.89,8.94,8.85,8.94,8.96,8.92),
c(8.84,8.9,8.82,8.92,8.93,8.91),
c(8.79,8.85,8.79,8.9,8.94,8.92),
c(8.79,8.88,8.81,8.9,8.95,8.92),
c(8.8,8.82,8.78,8.91,8.94,8.92),
c(8.75,8.78,8.77,8.91,8.95,8.92),
c(8.8,8.8,8.77,8.91,8.95,8.94),
c(8.74,8.81,8.76,8.93,8.98,8.99),
c(8.89,8.99,8.92,9.1,9.13,9.11),
c(8.97,8.97,8.91,9.09,9.11,9.11),
c(9.04,9.08,9.05,9.25,9.28,9.27),
c(9,9.01,9,9.2,9.23,9.2),
c(8.99,8.99,8.98,9.18,9.2,9.19),
c(8.93,8.97,8.97,9.18,9.2,9.18)
)
dim(z) <- c(15,6)
z2 <- z + 1
z3 <- z - 1
fig <- plot_ly(showscale = FALSE)
fig <- fig %>% add_surface(z = ~z)
fig <- fig %>% add_surface(z = ~z2, opacity = 0.98)
fig <- fig %>% add_surface(z = ~z3, opacity = 0.98)
fig
我尝试用我自己的数据复制这个示例 - 我能够分别绘制每个表面,但我无法弄清楚如何将这些表面堆叠在一起。例如:
library(plotly)
#plot1
X1 <- seq(0,100,1)
Y1 <- seq(0,100,1)
DF <- expand.grid(X1,Y1)
DF$Z1 <- sin(DF$Var1) + cos(DF$Var2)
Z1 <- matrix(DF$Z1, nrow = 100)
plot_ly(y = ~Y1, x = ~X1, z=~Z1) %>% add_surface()
#plot2
X2 <- seq(0,100,1)
Y2 <- seq(0,100,1)
DF2 <- expand.grid(X2,Y2)
DF2$Z2 <- -sin(DF2$Var1) + 0.5*cos(DF2$Var2)
Z2 <- matrix(DF2$Z2, nrow = 100)
plot_ly(y = ~Y2, x = ~X2, z=~Z2) %>% add_surface()
#plot3
X3 <- seq(0,100,1)
Y3 <- seq(0,100,1)
DF3 <- expand.grid(X3,Y3)
DF$Z3 <- DF3$Var2^2 + DF3$Var1^2
Z3 <- matrix(DF3$Z3, nrow = 100)
plot_ly(y = ~Y3, x = ~X3, z=~Z3) %>% add_surface()
但是当我将它们堆叠在一起时,这不起作用:
#### Stack on Top
fig <- plot_ly(y = ~DF$Y, x = ~DF$X, z=~DF$Z1) %>% add_surface()
fig <- fig %>% add_surface(z = ~Z2, opacity = 0.98)
fig <- fig %>% add_surface(z = ~Z3, opacity = 0.98)
这会产生以下错误:
Error: z must be a numeric matrix
谁能告诉我我做错了什么?
谢谢
【问题讨论】:
【参考方案1】:您只需要在引用提供给 plot_ly 的 data
参数的 data.frame 时添加“~”。当您尝试访问当前环境中的变量时,请勿使用它。
请检查以下内容
library(plotly)
DF <- data.frame(X = seq(0,100,1), Y = seq(0,100,1))
DF <- cbind(DF, expand.grid(DF$X, DF$Y))
DF$Z1 <- sin(DF$Var1) + cos(DF$Var2)
Z1 <- matrix(DF$Z1, nrow = 100)
DF$Z2 <- -sin(DF$Var1) + 0.5*cos(DF$Var2)
Z2 <- matrix(DF$Z2, nrow = 100)
DF$Z3 <- DF$Var2^2 + DF$Var1^2
Z3 <- matrix(DF$Z3, nrow = 100)
fig <- plot_ly(y = DF$y, x = DF$X, z=Z1, type = "surface")
fig <- fig %>% add_surface(z=Z2, opacity = 0.98)
fig <- fig %>% add_surface(z=Z3, opacity = 0.98)
fig
【讨论】:
以上是关于R:将 Plotly 图堆叠在彼此之上的主要内容,如果未能解决你的问题,请参考以下文章
水平堆叠的独特 100% 条形图 plotly python
R语言ggplot2可视化:使用plotly包的subplot函数将多个ggplot2可视化结果组合在一起形成组合plotly图(Multiple ggplot2 plots with plotly)