使用循环变量在 matplotlib 中指定颜色

lov*_*eed 5 python matplotlib

我有很多数据文件,我想在同一个图上绘制所有这些文件,但颜色不同。我正在使用以下代码

from pylab import loadtxt, average, std, argsort
from os import listdir
from fnmatch import fnmatch
import matplotlib.pyplot as plt


a=[]
for file in listdir('.'):
   if fnmatch(file,'A10data*'):
      a+=[str(file)]



for file in a:
  T,m_abs, m_abs_err,m_phy,m_phy_err = loadtxt(file,unpack=True)
  T_sort = argsort(T)
  plt.xlim(0.00009,10.1)
  plt.ylim(-1,350)

  plt.semilogx(T[T_sort],m_abs[T_sort],'ro-')
  plt.errorbar(T[T_sort],m_abs[T_sort],yerr=m_abs_err[T_sort],fmt='ro')
  plt.semilogx(T[T_sort],m_phy[T_sort],'r^-')
  plt.errorbar(T[T_sort],m_phy[T_sort],yerr=m_phy_err[T_sort],fmt='r^')


plt.show()
Run Code Online (Sandbox Code Playgroud)

可能我可以使用整数并使用整数来指定绘图的颜色。有人可以帮我语法吗?

rep*_*cus 2

如果文件/绘图的数量很小,您可以创建一个与上面称为数组相同长度的颜色数组:如下所示:


colors = ["red", "blue" , "green", "orange", "purple"]
ncolor = 0
for file in a:
    plt.semilogx(T[T_sort], m_abs[T_sort], 'o-', color=colors[ncolor])
    ncolor+=1
Run Code Online (Sandbox Code Playgroud)

  • 更强大和Pythonic:'zip(a, itertools.cycle(colors))',它自动循环颜色。 (3认同)