Patthebug
Patthebug

Reputation: 4787

Generating multiple heatmaps with the same gradient

I'm trying to create multiple heatmaps using matplotlib using the same code. Ofcourse the data is different for all these heatmaps. And because of this, the intensity of colors across heatmaps is different. Is there a way I can make sure that the range of intensity remains the same? All my values in the heatmaps lie between 0 and 1. So I want the color of the value 0.2 in heatmap1 to look exactly the same as the color of the value 0.2 in heatmap2, even though both heatmaps could have different ranges.

I apologize for the somewhat confusing language of the question, but I don't know how to explain it better.

Here's the code that I'm using to generate heatmaps:

from matplotlib import pyplot as plt

def show_values(pc, fmt="%.2f", **kw):
    '''
    Heatmap with text in each cell with matplotlib's pyplot
    Source: http://stackoverflow.com/a/25074150/395857 
    By HYRY
    '''
#     from itertools import izip
    try:
        # Python 2
        from itertools import izip
    except ImportError:
        # Python 3
        izip = zip
    pc.update_scalarmappable()
    ax = pc.get_axes()
    for p, color, value in izip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
        x, y = p.vertices[:-2, :].mean(0)
        if np.all(color[:3] > 0.5):
            color = (0.0, 0.0, 0.0)
        else:
            color = (1.0, 1.0, 1.0)
        ax.text(x, y, fmt % value, ha="center", va="center", color=color, **kw)


df= pd.read_csv("filepath", header=None)
fig, ax = plt.subplots(figsize=(20, 10)) 
heatmap = plt.pcolor(df,cmap=matplotlib.cm.Blues)
ax.set_yticks(np.arange(df.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(df.shape[1]) + 0.5, minor=False)
ax.set_xticklabels(xlabels, minor=False, rotation=45)
ax.set_yticklabels(ylabels, minor=False)
plt.ylim( (0, df.shape[0]) )
plt.gca().invert_yaxis()
plt.title("plot title")
show_values(heatmap)
plt.show()

Any help would be much appreciated.

Upvotes: 0

Views: 1363

Answers (1)

mauve
mauve

Reputation: 2763

Determine your minimum and maximum and specify them in the code

plt.pcolor(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)

I pulled this from this example

Upvotes: 2

Related Questions