cmap and color bar being compressed from the assigned range

19 views Asked by At

This is a sample code. I want to build a heat map with values limited from 0.5 to 0.6, but with a linear color scale ranging [(0, 'yellow'), (0.25, 'orange'), (1, 'darkred')]. However, since there are not values near 0 and 1, it compresses the color scale to be from 0.5 to 0.6 (shown below in the images).

import numpy as np
import matplotlib.pyplot as plt

# Define the range of values for x and y axes
xs = np.linspace(0.1, 0.9, 100)
ys = np.linspace(0, 1, 100)

# Initialize an array to store phases
phases = np.zeros((len(ys), len(xs)))

# Generate random phases for each combination of x and y
for i, y in enumerate(ys):
    for j, x in enumerate(xs):
        phases[i, j] = np.random.uniform(0.5, 0.6)

# Plot the phases as colors
colors = [(0, 'yellow'), (0.25, 'orange'), (1, 'darkred')]
cmap = plt.cm.colors.LinearSegmentedColormap.from_list('cphase', colors)
fig, ax = plt.subplots()
im = ax.pcolormesh(xs, ys, phases, cmap=cmap)

# Set axes information that is common across plots
ax.set(xlim=[0.1, 0.9], ylim=[0, 1])
ax.set_box_aspect(1)

# Add a color bar with ticks at 0, 0.5, and 1
cbar = plt.colorbar(im)
cbar.set_ticks([0, 0.5, 1])

plt.show()

This is the output for the above code block.

Original Output

Now, if I manually change phases[0][0] = 0 and phases[99][99] = 1, this is what the graph looks like (and what I am to achieve without the manual change).

Expected Output

0

There are 0 answers