簡體   English   中英

如何在 Matplotlib 中疊加兩個二維直方圖?

[英]How to overlay two 2D-histograms in Matplotlib?

我在同一個系統中有兩個數據集(對應於氫原子的時間位置數據和氧化鋁原子的時間位置數據)。 我想通過使用 matplotlib 疊加兩個hist2d圖來繪制每個元素的密度。

我目前通過在第二個hist2d上設置一個 alpha 值來做到這一點:

    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)

我確實得到了我想要的情節,但是由於 alpha 值,顏色似乎褪色了。 有沒有更正確的方法來生成這樣的圖?

我目前收到的情節。如您所見,顏色有點褪色

實現此目的的一種方法是向現有顏色圖的較低級別添加淡化 alpha:

在此處輸入圖像描述

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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM