簡體   English   中英

如何在python中通過分類變量繪制直方圖網格?

[英]How to plot grid of histograms by categorical variable in python?

我有一個包含50個數字變量和1個類別變量的數據集(segment_hc_print,具有6個類別)。 我想通過繪制直方圖網格來查看每個類別中每個變量的分布情況,其中每一行代表一個類別,一列代表變量,網格中的每個單元格都是一個直方圖。 我正在嘗試下面的代碼為單個變量生成網格:

def grid_histogram(variable, bins):
    fig = plt.figure(figsize=(20,10))
    fig.set_size_inches(10,10, forward = True)
    fig.suptitle(variable, fontsize = 8)
    plt.locator_params(numticks = 4)

    for i in np.arange(0, 6, 1):
        ax = plt.subplot(6,1,i+1)
        ax.hist(sensor_df_print_sample_v2[sensor_df_print_sample_v2.segment_hc_print == i][variable], bins)
        ax.set_title("cluster = " + str(i), fontsize = 5)
        ymin, ymax = ax.get_ylim()
        ax.set_yticks(np.round(np.linspace(ymin, ymax, 3), 2))
        xmin, xmax = ax.get_xlim()
        ax.set_xticks(np.round(np.linspace(xmin, xmax,3),2))
        plt.setp(ax.get_xticklabels(), rotation = 'vertical', fontsize = 4)

    fig.tight_layout()
    fig.savefig(str(variable) + '_histogram.pdf')
    plt.show()

這就是我得到的: 直方圖樣本

如何生成此類直方圖的網格,每個直方圖堆疊在另一個變量的右側? 下面的代碼生成我需要的理想直方圖大小。 樣本直方圖

如果我理解正確,則可以使用plt.subplots()創建一個網格。 在下面的示例中,我將前5個變量繪制為列:

nr_of_categories = 6
nr_of_variables = 5

fig, ax = plt.subplots(nrows = nr_of_categories, cols = nr_of_variables, figsize = (20, 20))

for category in np.arange(0, nr_of_categories):
  for variable in np.arange(0, nr_of_variables):
    ax[category, variable].hist(sensor_df_print_sample_v2[sensor_df_print_sample_v2.segment_hc_print == i][variable], bins)

    # and then the rest of your code where you replace ax with ax[category, variable]


暫無
暫無

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

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