python matplotlib:如何使用fill_between和colormap来填充2D图的背景?

时间:2013-07-15 17:22:10

标签: python matplotlib

我正在尝试从3列数据集中制作一个简单的2d图,例如y = f(x)且z = f(x)。我想绘制xy并希望使用颜色显示z。例如,[x1,x2,min(y),max(y)] ...之间的矩形区域将根据z的值填充背景颜色。我尝试使用fill_between但无法将colormap与之关联。我是matplotlib和python的新手。我非常感谢您的意见/建议。

编辑:我没有准确的情节,但我会尝试在下图sample plot

的帮助下解释我的查询

在x = 0.5到x = 1之间,z = 1             x = 1.0,x = 1.5,z = 2 ....

所以我想覆盖x = 0.5到x = 1(min(y)到max(y)],其中一些颜色对应于z = 1,并且x = 1,x = 1.5,z = 2等等。我想使用色彩图显示这种变化,并在右侧显示此颜色条。

2 个答案:

答案 0 :(得分:2)

这里的解决方案是那些想要的人不能使用contourf或者由于某些其他原因需要fill_between(如本例中的不规则网格数据)。

import numpy as np
import matplotlib.pyplot as plt
from random import randint, sample
import matplotlib.colorbar as cbar

# from Numeric import asarray
%matplotlib inline

# The edges of 2d grid
# Some x column has varying rows of y (but always the same number of rows) 
# z array that corresponds a value in each xy cell

xedges = np.sort(sample(range(1, 9), 6))
yedges = np.array([np.sort(sample(range(1, 9), 6)) for i in range(5)])
z = np.random.random((5,5))

f, ax = plt.subplots(1, sharex=True, figsize=(8,8))
f.subplots_adjust(hspace=0)
ax.set_ylabel(r'y')
ax.set_xlabel(r'x')
ax.set_ylim(0,10)
ax.set_xlim(0,10)

c = ['r','g','b','y','m']

normal = plt.Normalize(z.min(), z.max())
cmap = plt.cm.jet(normal(z))

# plot showing bins, coloured arbitrarily.
# I want each cell coloured according to z.
for i in range(len(xedges)-1):
    for j in range(len(yedges)):
        ax.vlines(xedges[i],yedges[i][j],yedges[i][j+1],linestyle='-')
        ax.hlines(yedges[i][j],xedges[i],xedges[i+1],linestyle='-')
        ax.vlines(xedges[i+1],yedges[i][j],yedges[i][j+1],linestyle='-')
        ax.hlines(yedges[i][j+1],xedges[i],xedges[i+1],linestyle='-')

        ax.fill_between([xedges[i],xedges[i+1]],yedges[i][j],yedges[i][j+1],facecolor=cmap[i][j][:])


cax, _ = cbar.make_axes(ax) 
cb2 = cbar.ColorbarBase(cax, cmap=plt.cm.jet,norm=normal) 

这给出了

x-y grid, coloured as function of z

答案 1 :(得分:0)

听起来我应该使用contourf

http://matplotlib.org/examples/pylab_examples/contourf_demo.html

这会将x作为一些因变量,生成y = y(x)z = z(x)。您的z似乎不依赖y,但contourf仍可以处理此问题。

举个简单的例子:

import pylab as plt
x = plt.linspace(0,2,100)
y = plt.linspace(0,10,100)

z = [[plt.sinc(i) for i in x] for j in y]

CS = plt.contourf(x, y, z, 20, # \[-1, -0.1, 0, 0.1\],
                        cmap=plt.cm.rainbow)
plt.colorbar(CS)
plt.plot(x,2+plt.sin(y), "--k")

有许多变化,但希望这能抓住你正在寻找的元素

enter image description here