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

5

我有很多数据文件,想在同一张图表上绘制它们,但需要使用不同的颜色。我正在使用以下代码:

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()

我可以使用一个整数来指定图表的颜色。有人可以帮我处理语法吗?


顺便提一下:你应该查看一下 glob 标准模块。 - Eric O. Lebigot
1个回答

2

如果文件/图案的数量较少,您可以创建一个与名为a的数组长度相同的颜色数组:例如:


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


1
稍微更Pythonic的写法是使用 for file,c in zip(a,colors):plt.semilogx(...,color=c) - tacaswell
3
更为健壮和符合Python风格的写法是:'zip(a, itertools.cycle(colors))',它会自动循环遍历颜色序列。 - Eric O. Lebigot

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接