4

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

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。我希望我绘制的每个矩形都是与矩形中标量字段的值相对应的颜色。

4

2 回答 2

8

您可以使用 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()

在此处输入图像描述

于 2012-05-10T13:10:40.770 回答
3

改编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")

它给出了以下图形:

在此处输入图像描述

于 2019-01-31T11:42:45.593 回答