Python中的矩形颜色

时间:2012-05-10 12:23:50

标签: python colors matplotlib

要在我的绘图中添加一个矩形,我通常会使用以下代码:

ret=Rectangle((x_l[i]-dx,y_l[i]-dx),width=dx,height=dx,facecolor='red',linestyle='solid')
ax=gca()
ax.add_patch(ret)

但是我想知道是否有可能以不同的方式给出颜色。我希望我的矩形根据颜色条进行着色。我会尝试更好地解释它。每个矩形代表一个单元格,在每个单元格中我定义一个标量字段。我的标量字段范围从min_valmax_val。我希望我绘制的每个矩形都是与矩形中标量字段的值相对应的颜色。

2 个答案:

答案 0 :(得分:7)

您可以使用ColorMap计算的颜色绘制每个Rectangle:

import matplotlib.colorbar as cbar
import pylab as pl
import numpy as np

N = 50
xs = np.random.randint(0, 100, N)
ys = np.random.randint(0, 100, N)
ws = np.random.randint(10, 20, N)
hs = np.random.randint(10, 20, N)
vs = np.random.randn(N)
normal = pl.Normalize(vs.min(), vs.max())
colors = pl.cm.jet(normal(vs))

ax = pl.subplot(111)
for x,y,w,h,c in zip(xs,ys,ws,hs,colors):
    rect = pl.Rectangle((x,y),w,h,color=c)
    ax.add_patch(rect)

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

ax.set_xlim(0,120)
ax.set_ylim(0,120)
pl.show()

enter image description here

答案 1 :(得分:1)

调整HYRY的答案以提供不依赖pylab的解决方案:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np
import matplotlib.colorbar as cbar

fig,ax=plt.subplots(1)

rng=6
plt.ylim(0,rng)
plt.xlim(0,rng)

N = 30
x = np.random.rand(N)*rng
y = np.random.rand(N)*rng
colors=np.random.rand(N)
normal = plt.Normalize(0,1) # my numbers from 0-1

cmap=plt.cm.RdYlBu_r
c=cmap(colors)

for i in range(N):
    val=0.5
    rect=patches.Rectangle((x[i],y[i]),0.3,0.3,
                            edgecolor='black',
                            linewidth = 1,
                            facecolor = c[i],
                            ) 
    ax.add_patch(rect)

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

plt.savefig("test.png")

给出以下图形:

enter image description here