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

Matplotlib Colormaps使用:如何为每条折线/研究对象分配独立颜色

解决Matplotlib指定Colormap时多条折线颜色重复问题

问题原因

你的代码出现所有折线颜色相同的问题,核心有两个错误:

  • 变量名覆盖:循环变量Subject初始为受试者名称字符串,后续你直接将读取到的数值数组赋值给了Subject变量,执行Subjects.index(Subject)时相当于在字符串列表中查找numpy数组,永远只能匹配到第一个索引,所以所有折线都取了颜色列表的第一个颜色。
  • 颜色列表重复生成:你将colormap加载、颜色列表生成的逻辑放在了for循环内部,每次循环都会重复生成完全相同的颜色列表,属于冗余操作。

修正后的代码

# Initialize
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from matplotlib.pyplot import cm

# Numpy.loadtxt – Loads data from a textfile. Scipy.signal.welch – Creation of the FFT/power-spectrum. f, Pxx_den creates the ideal frequencies/FFT (f, Welch = Power Spectrum or Power Spectral Density)
Subjects = ["Subject1", "Subject2", "Subject3", "Subject4", "Subject5", "Subject7", "Subject8", "Subject9", "Subject10", "Subject11", "Subject12", "Subject13",
            "Subject14", "Subject15", "Subject16", "Subject17", "Subject18", "Subject19", "Subject20", "Subject22", "Subject23", "Subject24", "Subject25"]

# 提前生成颜色列表,仅执行一次
cmap = plt.get_cmap("plasma") # 这里可替换为你需要的colormap,比如inferno、viridis等
slicedCM = cmap(np.linspace(0, 1, len(Subjects)))

# 改用索引遍历,避免变量名冲突
for idx, subject_name in enumerate(Subjects):
    subject_data = np.loadtxt("/volumes/SanDisk2/fmri/dataset/processed/extracted_timeseriespython/restingstate/{0}/TimeSeries.SPC.Core_ROI.{0}.txt".format(subject_name), comments="#", delimiter=None,
                         converters=None, skiprows=0, usecols=0, unpack=False, ndmin=0, encoding=None, max_rows=None, like=None)

    f, Welch = signal.welch(subject_data, fs=1.0, window="hann", nperseg=None, noverlap=None, nfft=1024, detrend="constant", return_onesided=True, scaling="density", axis=-1, average="mean")
    # 直接用索引取对应颜色
    plt.plot(f, Welch, c=slicedCM[idx]) 
    

# Grid labels
plt.title("Power Spectrum for all subjects", fontsize=12, fontweight="bold")
plt.xlabel("Log Frequency [Hz]", fontsize=11, fontweight="bold")
plt.ylabel("Log Power [Hz]", fontsize=11, fontweight="bold")

# Grid dimenions and style
plt.xlim([0.005, 0.2]) # x-axis range
plt.ylim([0, 100]) # y-axis range

plt.xticks(np.arange(0, 0.21, 0.025)) # x ticks range (start, end, step)
plt.yticks(np.arange(0, 101, 10)) # y ticks range (start, end, step)

plt.grid(True) # Show grid
plt.rc("axes", axisbelow=True) # Grid behind figures
plt.rc("grid", linestyle="-", color="black") # Grid look

# Show result
plt.show()

补充说明

  • 该代码完全兼容你使用的Matplotlib 3.5.0版本
  • 调整np.linspace(0,1, len(Subjects))的起止值可以裁剪colormap的使用范围,避免用到过浅/过深的颜色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:36:04