2012-04-26 61 views
5

新的matplotlib用户在这里。我试图绘制颜色编码的数据线,或更好的是用颜色编码的数据范围。沿y轴的颜色编码间隔。一个粗略的演示脚本如下:Matplotlib - 网格和绘图颜色编码的y值/数据范围

import matplotlib.pyplot as plt 

# dummy test data 
datapoints = 25 
maxtemps = [ 25, 24, 24, 25, 26, 27, 22, 21, 22, 19, 17, 14, 13, 12, 11, 12, 11, 10, 9, 9, 9, 8, 9, 9, 8 ] 
mintemps = [ 21, 22, 22, 22, 23, 24, 18, 17, 16, 14, 10, 8, 8, 7, 7, 6, 5, 5, 5, 4, 4, 4, 3, 4, 3 ] 
times = list(xrange(datapoints)) 

# cap a filled plot at a given level 
def capped(indata, cap): 
    outdata = [0] * datapoints 
    lcount = 0 

    while lcount < datapoints: 
     if indata[lcount] > cap: 
      outdata[lcount] = cap 
     else: 
      outdata[lcount] = indata[lcount] 
     lcount += 1 
    return outdata 

fig = plt.figure() 

ax1 = fig.add_subplot(111) 
ax1.fill_between(times, 0, maxtemps, color='#FF69B4', zorder=1, linewidth=0.1) 
ax1.fill_between(times, 0, capped(maxtemps,25), color='#F08228', zorder=2, linewidth=0.1) 
ax1.fill_between(times, 0, capped(maxtemps,20), color='#E6AF2D', zorder=3, linewidth=0.1) 
ax1.fill_between(times, 0, capped(maxtemps,15), color='#E6DC32', zorder=4, linewidth=0.1) 
ax1.fill_between(times, 0, capped(maxtemps,10), color='#A0E632', zorder=5, linewidth=0.1) 
ax1.fill_between(times, 0, capped(maxtemps,5), color='#00DC00', zorder=6, linewidth=0.1) 
ax1.fill_between(times, 0, mintemps, color='#FFFFFF', zorder=7, linewidth=0.1) 
plt.setp(ax1.get_xticklabels(), visible=False) 
ax1.grid(True, zorder=8) 
ylim(0) 
plt.draw() 
plt.show() 

大部分的工作,但它提出了两个问题。

  1. 有没有更多的,直接的,优雅的方式来实现这个相同的效果,我不知道matplotlib功能?那就是要绘制(比方说)时间序列数据的一维数组,或者说明两组这样的数据之间的范围(例如最大温度,最小温度)?

  2. 尽我所能,我不能说服网格线在图上。他们似乎总是坐在第一组绘图数据的顶部,然后被随后绘制的数据掩埋,使得绘图的下半部分留空。 zorder的使用似乎被忽略。

非常感谢。

回答

9

要回答你的第二个问题:

你可以设置所有的fill_between顺序,以便0.1,0.2,0.3 ...

网格线属于X轴Y轴和,而x轴的ZORDER和Y轴是2.5。因此,任何小于2.5的zorder将显示在网格线下方。

我写的与你类似的一些代码,但使用循环和numpy.interpnumpy.clip做剪辑剧情:

import pylab as pl 
import numpy as np 
maxtemps = [ 25, 24, 24, 25, 26, 27, 22, 21, 22, 19, 17, 14, 13, 12, 11, 12, 11, 10, 9, 9, 9, 8, 9, 9, 8 ] 
mintemps = [ 21, 22, 22, 22, 23, 24, 18, 17, 16, 14, 10, 8, 8, 7, 7, 6, 5, 5, 5, 4, 4, 4, 3, 4, 3 ] 
times = list(xrange(len(mintemps))) 

colors = [ 
    (25, '#FF69B4'), 
    (20, '#F08228'), 
    (15, '#E6AF2D'), 
    (10, '#E6DC32'), 
    (5, '#A0E632'), 
    (0, '#00DC00') 
] 

# change 300 to larger number if you need more accuracy. 
x = np.linspace(times[0], times[-1], 300) 
maxt = np.interp(x, times, maxtemps) 
mint = np.interp(x, times, mintemps) 

last_level = np.inf 
for level, color in colors:  
    tmp_min = np.clip(mint, level, last_level) 
    tmp_max = np.clip(maxt, level, last_level) 
    pl.fill_between(x, tmp_min, tmp_max, lw=0, color=color) 
    last_level = level 

pl.grid(True) 
pl.show() 

enter image description here

相关问题