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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-05-31 11:00:00 +0000
Seen: 10 times
Last updated: Mar 27 '22
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?