簡體   English   中英

多個直方圖,每個直方圖對應一個 x 軸的標簽,在同一個圖 matplotlib 上

[英]Multiple Histograms, each for a label of x-axis, on the same graph matplotlib

我正在嘗試繪制一個圖表,以顯示男性和女性針對不同年齡組的特定活動的不同行為。

所以,如果年齡組是:['1-10','11-20','21-30'...] 我想為每個年齡組繪制一個直方圖(每個年齡范圍都是x 軸上的標簽),用於進行活動的男性和女性。 我知道如何在一個圖中繪制兩個直方圖,但我不知道如何並行繪制多個直方圖,尤其是當每個直方圖都針對給定的 x 標簽時。

有人可以幫忙嗎?

我不確定你是否想要一個圖中的兩個直方圖,但如果我生成一些隨機數據:

import numpy as np
import matplotlib.pyplot as plt
age = ['{}-{}'.format(i*10, (i+1)*10) for i in range(10)]
males = np.random.randint(0,100,10)
females = np.random.randint(0,100,10)

如果您需要從某些數據手動創建直方圖,您可以使用numpy而不是 matplotlib 直方圖( male_datafemale_data是您插入plt.hist() ):

bins = [i*10 for i in range(11)] # = [0,10,20,30,40,50,60,70,80,90,100]
males , _ = np.histogram(male_data, bins=bins)
females , _ = np.histogram(female_data, bins=bins)

然后將其繪制為bar (我已經從matplotlib 示例頁面中改編了其中的一些內容)我得到了一些可能是您想要的東西:

fig, ax = plt.subplots()
# Normalize the counts by dividing it by the sum:
ax.bar(np.arange(10)-0.15, males/np.sum(males), width=0.1, color='b', label='male')
ax.bar(np.arange(10)+0.05, females/np.sum(females), width=0.1, color='r', label='female')
ax.set_xticks(np.arange(10))
ax.set_xticklabels(age)
ax.legend()
ax.set_xlim(-0.5,9.5)
plt.show()

在此處輸入圖片說明

或者你想用共享 y 軸來分開地塊?

fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.bar(np.arange(10)-0.3, 100*males/np.sum(males), width=0.6, color='b', label='male')
ax2.bar(np.arange(10)-0.3, 100*females/np.sum(females), width=0.6, color='r', label='female')
for i in (ax1, ax2):
    getattr(i, 'set_xticks')(np.arange(10))
    getattr(i, 'set_xticklabels')(age)
    getattr(i, 'set_xlabel')('Age range')
    getattr(i, 'set_ylabel')('People doing it (in percent)')
    getattr(i, 'set_xlim')(-0.5,9.5)
plt.show()

在此處輸入圖片說明

在第二個示例中,您可能需要減小文本大小,以便正確顯示年齡范圍...

暫無
暫無

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

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