[英]Colors of Rectangles in python
To add a rectangle to my plot I usually use this code: 要在我的绘图中添加矩形,我通常使用以下代码:
ret=Rectangle((x_l[i]-dx,y_l[i]-dx),width=dx,height=dx,facecolor='red',linestyle='solid')
ax=gca()
ax.add_patch(ret)
However I was wondering if was possible to give the color in a different way. 但是我想知道是否有可能以不同的方式给出颜色。 I want my rectangle to be colored according to a colorbar. 我希望我的矩形根据颜色条进行着色。 I'll try explain it better. 我会尝试更好地解释它。 Every rectangle represent a cell and in every cell I define a scalar field. 每个矩形代表一个单元格,在每个单元格中我定义一个标量字段。 My scalar field ranges from min_val
to max_val
. 我的标量字段范围从min_val
到max_val
。 I want every rectangle that I drawn to be color that correspond to the value of the scalar field in the rectangle. 我希望我绘制的每个矩形都是颜色,对应于矩形中标量字段的值。
You can draw every Rectangle with the color calculated by ColorMap: 您可以使用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()
Adapting the answer of HYRY to provide a solution that does not rely on pylab: 调整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")
which gives the follow graphic: 它给出了以下图形:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.