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

如何在R中为三元图自定义顶点颜色(Ternary/ggtern包)

自定义顶点颜色的三元图实现方案

Ternary包的自定义颜色实现

TernaryPointValues函数默认调用rgb生成基于三顶点RGB的颜色,无法直接传入自定义顶点色,但可以通过自定义颜色插值函数替代默认的rgb,实现指定顶点色的渐变效果:

library(Ternary)

# 定义三个顶点的自定义颜色
vertex_colors <- c("#016699", "#769022", "#F99C1C")

# 创建自定义颜色插值函数:基于三个顶点色做线性插值
custom_color <- function(a, b, c) {
  total <- a + b + c
  # 归一化三元分量,确保总和为1
  a_norm <- a / total
  b_norm <- b / total
  c_norm <- c / total
  
  # 使用colorRamp生成插值后的RGB值
  color_ramp <- colorRamp(vertex_colors)
  rgb_vals <- color_ramp(c(a_norm, b_norm, c_norm)) / 255
  rgb(rgb_vals[1], rgb_vals[2], rgb_vals[3])
}

# 绘制带自定义颜色的三元图
TernaryPlot()
color_matrix <- TernaryPointValues(custom_color)
ColourTernary(color_matrix, spectrum = NULL)

该方案通过colorRamp构建自定义颜色渐变规则,让TernaryPointValues生成符合需求的颜色矩阵,最终渲染出顶点为指定颜色的三元图。

ggtern包的替代解决方案

如果更倾向于ggplot2生态的绘图方式,ggtern包提供了更灵活的自定义空间,实现代码如下:

library(ggtern)
library(dplyr)

# 自定义顶点颜色
vertex_colors <- c("#016699", "#769022", "#F99C1C")

# 生成三元网格数据
tern_grid <- create_grid(breaks = 50) %>%
  as.data.frame() %>%
  rename(x = L, y = T, z = R) %>% # L/T/R对应三元图的三个顶点,可按需调整
  filter(x >= 0, y >= 0, z >= 0)

# 为每个网格点计算自定义插值颜色
tern_grid <- tern_grid %>%
  rowwise() %>%
  mutate(
    fill_color = rgb(
      colorRamp(vertex_colors)(c(x, y, z))[1]/255,
      colorRamp(vertex_colors)(c(x, y, z))[2]/255,
      colorRamp(vertex_colors)(c(x, y, z))[3]/255
    )
  )

# 绘制三元图
ggtern(data = tern_grid, aes(x = x, y = y, z = z)) +
  geom_raster(aes(fill = fill_color), interpolate = TRUE) +
  scale_fill_identity() + # 直接使用生成的颜色值
  theme_bw() +
  theme_noarrows() + # 隐藏默认箭头
  labs(
    x = "Vertex 1 (#016699)",
    y = "Vertex 2 (#769022)",
    z = "Vertex 3 (#F99C1C)"
  )

这段代码通过生成三元网格数据,为每个点计算基于自定义顶点色的插值颜色,再用geom_raster填充,实现了和Ternary包类似的效果,同时保留了ggplot2的自定义扩展性。

内容的提问来源于stack exchange,提问作者Pablo Herreros Cantis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 23:10:07