簡體   English   中英

Matplotlib:使用不同的 colors 和不同的 alpha 並排繪制多個直方圖

[英]Matplotlib: plotting multiple histograms side by side with different colors and different alphas

我想將 plot 多個數據轉換成直方圖,其中每個數據集都有自己的顏色和 alpha 值。 我試過這個:

colors = ['red', 'green', 'blue']
alphas = [1.0, 0.7, 0.3]
plt.hist([data1, data2, data3], bins = 15, label=['Data 1', 'Data 2', 'Data 3'], color = colors, alpha = alphas)

但是,我收到以下錯誤:

alpha must be numeric or None, not <class 'list'>

但我希望每個直方圖都有不同的 alpha 值。 我怎樣才能做到這一點?

我嘗試按照@BigBen 在評論中的建議使用zip

datas = [data1, data2, data3]
colors = ['red', 'green', 'blue']
alphas = [1.0, 0.7, 0.3]
labels = ['Data 1', 'Data 2', 'Data 3']
plt.savefig('images/bla.png')
for data, label, color, alpha in zip(datas, labels, colors, alphas):
    plt.hist(data, bins=10, label=label, color=color, alpha=alpha)

然而,結果看起來是這樣的:

重疊直方圖

但我需要這樣的東西,但不同的 colors 有不同的 alpha 值:

不同的直方圖

matplotlib.colors.to_rgba是解決方案。 使用它,可以將 alpha 值添加到 colors。

red = matplotlib.colors.to_rgba('red', alpha=1)
green = matplotlib.colors.to_rgba('green', alpha=0.7)
blue = matplotlib.colors.to_rgba('blue', alpha=0.3)
colors = [red, green, blue]

plt.hist([data1, data2, data3], bins = 15, label=['Data 1', 'Data 2', 'Data 3'], color = colors)

在此處輸入圖像描述

暫無
暫無

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

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