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
. 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:
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With