我想将密度图和等值线图合并到一个图中,如下图所示,在 RStudio 中。我使用以下代码创建两个单独的密度图和等高线图:
library(MASS)
library(plotly)
set.seed(123)
lambda1 <- 4
k1 <- 3
theta1 <- 5
k2 <- 1
theta2 <- 5
num_simulations <- 1000
n <- rpois(num_simulations, lambda1)
n_truncated <- n[n > 0]
num_simulations <- length(n_truncated)
generate_gamma_sums <- function(counts, k, theta) {
sapply(counts, function(x) sum(rgamma(x, shape = k, scale = theta)))
}
ssx <- data.frame(
sx = generate_gamma_sums(n_truncated, k1, theta1),
sy = generate_gamma_sums(n_truncated, k2, theta2)
)
colnames(ssx) <- c("X", "Y")
density_data <- kde2d(ssx$X, ssx$Y, n = 50)
x_vals <- rep(density_data$x, each = length(density_data$y))
y_vals <- rep(density_data$y, length(density_data$x))
z_vals <- as.vector(density_data$z)
xlim <- range(density_data$x)
ylim <- range(density_data$y)
pdf_3d_plot <- plot_ly(x = ~x_vals, y = ~y_vals, z = ~z_vals, type = 'mesh3d', intensity = ~z_vals,
showscale = TRUE, colorscale = list(c(0, 1), c("black", "white"))) %>%
layout(
scene = list(
xaxis = list(title = "X-axis", range = xlim, showgrid = TRUE, zeroline = FALSE, showline = TRUE),
yaxis = list(title = "Y-axis", range = ylim, showgrid = TRUE, zeroline = FALSE, showline = TRUE),
zaxis = list(title = "Density", showgrid = TRUE, zeroline = FALSE),
camera = list(eye = list(x = 1.5, y = 1.5, z = 1.2))
),
title = list(text = "3D PDF Surface", x = 0.5)
)
contour_2d_plot <- plot_ly(x = density_data$x, y = density_data$y, z = density_data$z,
type = "contour",
contours = list(coloring = "none", showlabels = TRUE),
line = list(color = 'black')) %>%
layout(
xaxis = list(title = "X-axis", range = xlim, showgrid = TRUE, zeroline = FALSE, showline = TRUE),
yaxis = list(title = "Y-axis", range = ylim, showgrid = TRUE, zeroline = FALSE, showline = TRUE),
title = list(text = "2D Contour Plot", x = 0.5))
如何将图 1 (pdf_3d_plot) 和图 2 (contour_2d_plot) 合并为一个?
谢谢
自从您的问题被重新提出(感谢@Dour High Arch),我想我应该为您的问题提供完整的答案。
正如我在评论中所说,如果相对容易的话,组合表面和轮廓。
我只使用了你的代码
density_data <- kde2d(ssx$X, ssx$Y, n = 50)
创建绘图不需要其他代码。
如果您有任何疑问,请告诉我。
plot_ly(x = density_data$x, y = density_data$y, z = density_data$z,
type = "surface", contours = list(z = list(show = T, project = list(z = T)))) %>%
layout(scene = list(zaxis = list(nticks = 15), # to create 15 contour levels
camera = list(eye = list(x = 1.75, y = .9, z = -.2))))