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

如何为Python绘制的蝴蝶曲线不同层级翅膀褶皱设置不同颜色

示例图片

蝴蝶曲线分层着色实现方法

你目前使用的plt.plot会将整条曲线渲染为单一颜色,要区分不同层级的褶皱颜色,可以通过参数绑定颜色映射的方式实现,具体修改后的可运行代码如下:

import numpy as np
import matplotlib.pyplot as plt

def butterfly_curve(timestamps):
    x = np.zeros(timestamps.size)
    y = np.zeros(timestamps.size)
    
    for k in range(0, timestamps.size):
        r = np.exp(np.cos(timestamps[k])) - 2 * np.cos(4 * timestamps[k]) - (np.sin((timestamps[k]/12)))**5
        x[k] = np.sin(timestamps[k]) * r
        y[k] = np.cos(timestamps[k]) * r
    
    return x, y

time = np.arange(0, 12 * np.pi, 0.01)
x, y = butterfly_curve(time)

# 核心修改:使用散点图绑定参数t作为颜色映射依据
plt.scatter(x, y, c=time, cmap='plasma', s=0.5)
plt.xlabel('x')
plt.ylabel('y')
plt.axhline(0, color='black')
plt.axvline(0, color='black')
plt.title('Butterfly Curve')
# 可选:添加颜色条显示参数和颜色的对应关系
plt.colorbar(label='Parameter t')

# 可选:设置坐标轴等比例,避免蝴蝶形状拉伸变形
plt.axis('equal')
plt.show()

可调参数说明

  • cmap:可替换为任意matplotlib内置配色方案,常见可选值有viridis、rainbow、RdYlBu等,调整到褶皱分层视觉区分最清晰即可
  • s:调整散点的大小,数值越小线条越细,可根据显示效果自行调整

如果需要手动指定每个褶皱的固定颜色,也可以将c参数传入的time数组按照你划分的褶皱区间替换为对应分类标签,再配合ListedColormap自定义配色即可。如果需要更高的绘制性能,也可以使用LineCollection将曲线按参数区间分段后分别着色,运行效率比散点图更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:36:04