You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用R语言persp函数绘制3D热力曲面并去除坐标轴箭头

R语言persp绘制多色3D曲面、去除坐标轴箭头方案

两个需求都可以通过基础persp函数的参数调整实现,不需要依赖第三方扩展包,具体实现方法如下:

核心实现逻辑

  • 多色热力效果:persp的col参数支持传入与曲面网格面片数量一致的颜色向量,只要将每个面片对应的产出值映射到渐变色板,就能实现按产出高低区分颜色的热力曲面效果。
  • 去除默认坐标轴箭头:persp没有单独隐藏坐标轴箭头的参数,直接设置axes=FALSE关闭默认带箭头的坐标轴,再通过函数返回的坐标变换矩阵手动绘制无箭头的坐标轴、刻度和标签即可。

完整可运行代码

# 初始化投入要素范围
N <- 100
labour <- seq(1, N, by = 1)
capital <- seq(1, N, by = 1)

# 定义柯布-道格拉斯生产函数
cobb_douglas <- function(capital, labour, alpha=0.7, beta=0.25){
  capital^alpha * labour^beta
}

# 计算全要素网格对应的产出值
production <- outer(capital, labour, cobb_douglas, alpha=0.5, beta=0.5)

# 自定义热力渐变色板(可根据需要调整颜色节点)
color_pal <- colorRampPalette(c("#2c7bb6", "#abd9e9", "#ffffbf", "#fdae61", "#d7191c"))
# 计算每个曲面面片的平均产出值,用于颜色匹配
facet_row_cnt <- length(capital) - 1
facet_col_cnt <- length(labour) - 1
facet_avg_z <- (
  production[-1, -1] + 
  production[-1, -(facet_col_cnt+1)] + 
  production[-(facet_row_cnt+1), -1] + 
  production[-(facet_row_cnt+1), -(facet_col_cnt+1)]
)/4
# 为每个面片分配对应颜色
facet_cols <- color_pal(100)[cut(facet_avg_z, breaks = 100)]

# 绘制主图,关闭默认带箭头的坐标轴
trans_mat <- persp(
  labour, capital, production,
  main = "Cobb Douglas Production Function",
  theta = -45, phi = 20,
  col = facet_cols,
  border = NA, # 隐藏面片边框,让颜色过渡更自然
  axes = FALSE,
  xlab = "劳动投入 L",
  ylab = "资本投入 K",
  zlab = "产出 Q"
)

# 手动添加无箭头坐标轴与刻度
# 劳动投入(X轴)
x_ticks <- seq(0, N, by = 20)
lines(trans3d(x_ticks, rep(1, length(x_ticks)), rep(0, length(x_ticks)), trans_mat))
text(
  trans3d(x_ticks, rep(1, length(x_ticks)), rep(-max(production)*0.05, length(x_ticks)), trans_mat),
  labels = x_ticks, cex = 0.8
)

# 资本投入(Y轴)
y_ticks <- seq(0, N, by = 20)
lines(trans3d(rep(1, length(y_ticks)), y_ticks, rep(0, length(y_ticks)), trans_mat))
text(
  trans3d(rep(1, length(y_ticks)), y_ticks, rep(-max(production)*0.05, length(y_ticks)), trans_mat),
  labels = y_ticks, cex = 0.8
)

# 产出(Z轴)
z_ticks <- seq(0, max(production), length.out = 5)
lines(trans3d(rep(1, length(z_ticks)), rep(1, length(z_ticks)), z_ticks, trans_mat))
text(
  trans3d(rep(-3, length(z_ticks)), rep(1, length(z_ticks)), z_ticks, trans_mat),
  labels = round(z_ticks, 1), cex = 0.8
)

调整说明

  • 如果需要更换配色风格,既可以修改colorRampPalette里的颜色值自定义渐变,也可以直接替换为R内置色板函数,比如heat.colors(100)、terrain.colors(100)。
  • 手动添加坐标轴时,text函数里的偏移参数(比如-max(production)*0.05、-3)可以根据实际生成的图幅微调,避免刻度标签和坐标轴重叠。

内容的提问来源于stack exchange,提问作者Jorge Paredes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 02:15:39