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

如何在R的Plotly包中为等高线图添加图案填充?

解决Plotly等高线图添加图案填充的问题

Plotly原生的contour类型并不支持像柱状图那样通过marker = list(pattern = ...)添加图案填充,但可以通过以下两种方法实现类似效果:

方法一:用ggplot2 + ggpattern + ggplotly

借助ggpattern包给等高线填充区域添加图案,再转换成Plotly交互式图:

首先安装并加载所需包:

install.packages(c("ggplot2", "ggpattern", "plotly"))
library(ggplot2)
library(ggpattern)
library(plotly)

创建示例数据并绘图:

# 生成示例数据
set.seed(123)
x <- seq(-5, 5, length.out = 50)
y <- seq(-5, 5, length.out = 50)
z <- outer(x, y, function(x, y) sqrt(x^2 + y^2))
df <- expand.grid(x = x, y = y)
df$z <- as.vector(z)

# 用ggplot2 + ggpattern绘制带图案的等高线填充图
p <- ggplot(df, aes(x = x, y = y, z = z)) +
  geom_contour_filled_pattern(
    aes(pattern_shape = after_stat(level)),
    pattern = "stripe",
    pattern_fill = "black",
    pattern_density = 0.1,
    pattern_spacing = 0.02
  ) +
  scale_pattern_shape_discrete() +
  theme_minimal()

# 转换为Plotly交互式图
ggplotly(p)

pattern参数还支持"circle"、"cross"、"x"等样式,可根据需求调整。

方法二:Plotly原生叠加散点图模拟图案

通过在等高线填充图上叠加不同形状的散点,模拟图案效果:

library(plotly)

# 生成示例数据
x <- seq(-5, 5, length.out = 50)
y <- seq(-5, 5, length.out = 50)
z <- outer(x, y, function(x, y) sqrt(x^2 + y^2))

# 绘制基础等高线填充图
p <- plot_ly(z = z, x = x, y = y, type = "contour", fill = "tonexty")

# 为不同等高线区间添加散点图案
z_levels <- contourLevels(z, nlevels = 5)
for (i in 1:(length(z_levels)-1)) {
  # 筛选当前区间内的点
  mask <- z >= z_levels[i] & z < z_levels[i+1]
  scatter_x <- x[col(mask)][mask]
  scatter_y <- y[row(mask)][mask]
  # 循环切换散点形状
  shape <- c("x", "circle", "+", "triangle-up")[i %% 4 + 1]
  # 添加散点图层
  p <- p %>% add_markers(
    x = scatter_x, y = scatter_y,
    marker = list(shape = shape, size = 3, color = "black", opacity = 0.7),
    showlegend = FALSE
  )
}

p

这种方法完全基于Plotly原生函数,需要手动处理区间数据,样式调整相对繁琐,但无需依赖额外绘图包。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 20:37:11