简体   繁体   中英

How to overlay two 2D-histograms in Matplotlib?

I have two datasets (corresponding with the time-positional data of hydrogen atoms and time-positional data of alumina atoms) in the same system. I want to plot the density of each element by overlaying two hist2d plots using matplotlib.

I am currently doing this by setting an alpha value on the second hist2d :

    fig, ax = plt.subplots(figsize=(4, 4))
    v = ax.hist2d(x=alx, y=aly,
                  bins=50, cmap='Reds')
    h = ax.hist2d(x=hx, y=hy,
                  bins=50, cmap='Blues',
                  alpha=0.7)
    ax.set_title('Adsorption over time, {} K'.format(temp))
    ax.set_xlabel('picoseconds')
    ax.set_ylabel('z-axis')
    fig.colorbar(h[3], ax=ax)
    fig.savefig(savename, dpi=300)

I do get the plot that I want, however the colors seem washed out due to the alpha value. Is there a more correct way to do generate such plots?

我目前收到的情节。如您所见,颜色有点褪色

One way to achieve this would be a to add fading alphas towards lower levels to the existing color maps:

在此处输入图像描述

import numpy as np
import matplotlib.pylab as pl
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap

# modify existing Reds colormap with a linearly fading alpha
red = pl.cm.Reds  # original colormap
fading_red = red(np.arange(red.N)) # extract colors
fading_red[:, -1] = np.linspace(0, 1, red.N) # modify alpha
fading_red = ListedColormap(fading_red) # convert to colormap

# data generation
random_1 = np.random.randn(10000)+1
random_2 = np.random.randn(10000)+1
random_3 = np.random.randn(10000)
random_4 = np.random.randn(10000)

# plot
fig, ax = plt.subplots(1,1)
plt.hist2d(x=random_3, y=random_4, bins=100, cmap="Blues")
plt.hist2d(x=random_1, y=random_2, bins=50, cmap=fading_red)
plt.show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM