You can use the normalize
method from the matplotlib.colors
module to normalize the data to the range of [0,1], and then pass this normalized data to the PatchCollection
as the facecolors
parameter. This will result in the center color being represented as 0.
Here's an example code snippet:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np
# Sample data
data = np.random.rand(5,5)
# Normalize the data to [0,1]
norm = colors.Normalize(vmin=0, vmax=1)
# Create patches
patches = []
for i in range(5):
for j in range(5):
# Create a rectangle for each data point
x = j
y = i
width = 1
height = 1
rect = Rectangle((x,y), width, height)
patches.append(rect)
# Create a PatchCollection with the normalized data
pc = PatchCollection(patches, cmap='coolwarm', edgecolor='black',
linewidth=1, alpha=0.8, facecolor=norm(data))
# Set colorbar
cbar = plt.colorbar(pc)
cbar.ax.set_ylabel("Data")
# Set axis limits
plt.xlim(0,5)
plt.ylim(0,5)
# Show plot
plt.show()
In this example, the vmin
and vmax
parameters of the Normalize
method are set to 0 and 1, respectively, to ensure that the color range is normalized to that range. The cmap
parameter is set to "coolwarm" to provide a diverging colormap.
Asked: 2021-05-31 11:00:00 +0000
Seen: 10 times
Last updated: Mar 27 '22