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

如何在python-ternary绘制的三元图中正确填充多边形区域?

解决python-ternary库三元坐标轴多边形填充问题

方法一:使用ternary库原生fill函数(推荐)

ternary库自带fill方法,无需手动转换坐标,直接传入三元坐标顶点即可完成填充,能避免大部分位置偏移和重复图形问题。

示例代码

import ternary
import matplotlib.pyplot as plt

# 定义多边形的三元坐标顶点(确保每个点的三个分量之和等于绘图scale值,此处scale=1,故x+y+z=1;顶点按顺时针/逆时针顺序排列)
polygon_points = [
    (0.2, 0.3, 0.5),
    (0.5, 0.2, 0.3),
    (0.4, 0.5, 0.1),
    (0.1, 0.4, 0.5)
]

# 创建三元绘图对象
fig, tax = ternary.figure(scale=1.0)

# 绘制多边形轮廓(可选)
tax.plot(polygon_points, color='black', linewidth=2)
# 填充多边形,设置颜色和透明度
tax.fill(polygon_points, color='lightblue', alpha=0.5)

# 配置绘图样式
tax.boundary()
tax.ticks(axis='lbr', linewidth=1, multiple=0.1)
tax.set_title("Filled Polygon in Ternary Plot")

plt.show()

常见问题排查

  • 位置偏移:检查所有顶点的三个分量之和是否与scale参数匹配(比如scale=1时必须满足x+y+z=1),不匹配会导致自动缩放偏移。
  • 重复图形:避免多次调用fill或plot处理同一组顶点。

方法二:结合Matplotlib Patches手动填充

若需更自定义的填充效果,可将三元坐标转换为笛卡尔坐标后,用Matplotlib的Polygon补丁实现填充,需注意调用正确的API避免TypeError。

示例代码

import ternary
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

fig, tax = ternary.figure(scale=1.0)
polygon_points = [
    (0.2, 0.3, 0.5),
    (0.5, 0.2, 0.3),
    (0.4, 0.5, 0.1),
    (0.1, 0.4, 0.5)
]

# 绘制轮廓
tax.plot(polygon_points, color='black', linewidth=2)

# 将三元坐标转换为当前绘图对象的笛卡尔坐标(必须使用tax对象的转换方法,匹配scale和布局)
cartesian_points = [tax.ternary_to_cartesian(point) for point in polygon_points]

# 创建Polygon补丁(默认自动闭合,无需重复第一个顶点)
poly = Polygon(cartesian_points, color='lightgreen', alpha=0.5)

# 关键:通过tax.ax获取Matplotlib的Axes对象,调用add_patch添加补丁
tax.ax.add_patch(poly)

# 配置样式
tax.boundary()
tax.ticks(axis='lbr', linewidth=1, multiple=0.1)
tax.set_title("Filled Polygon with Matplotlib Patch")

plt.show()

TypeError解决要点

  • 不要直接调用tax.add_patch,因为ternary的Tax对象无此方法,需使用tax.ax.add_patch操作底层Matplotlib Axes对象。
  • 确保转换后的笛卡尔坐标是(x, y)格式的元组/列表,避免格式错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:48:22