簡體   English   中英

如何在 Python3 中使用自定義的下溢/溢出箱 plot 刻面直方圖?

[英]How to plot facet histogram with customized underflow/overflow bins in Python3?

我有一個 pandas dataframe 有幾列(區域、日期、利潤)。 我想要按地區和日期划分的利潤直方圖。 但是利潤列數據的每邊都有一條長尾,這意味着有 5 條利潤低於 10 美元,280483 條利潤在 400 美元到 450 美元之間,然后有 6 條利潤大於 10 萬美元。

我想做的是創建一個帶有自定義箱的直方圖,以便它顯示 400-450 美元的多個箱,低於 400 美元的只有 1 個箱,450 美元以上的有 1 個箱,希望直方圖中的列高於相同寬度。

我現在擁有的:

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
fixed_bin = list(np.arange(400,450,5))
fixed_bin.insert(0,0)
fixed_bin.append(150000)
fig = sns.FacetGrid(df, col = 'region', row = 'date',
                    margin_titles = True, aspect = 1.4)
fig.map(sns.distplot, 'profit', kde = False, bins = fixed_bin, color = 'r')

但是,這給了我一個從 0 到 150000 的均勻分布的 X 軸。我的所有數據(在 400-450 之間)仍然擠在中間,很難看到中間部分的真實直方圖。 如何將兩端的尾部(下溢箱和溢流箱)制成兩個與中間箱寬度相同的小箱?

非常感謝您的幫助!!

我的第一個想法是分別進行分箱和繪圖。 但我找不到matplotlib.pyplot.barseaborn.barplot提供自定義 bin 大小。

所以我們必須欺騙seaborn.distplotmatplotlib.pyplot.hist (后面的 function)。

import numpy as np

import seaborn as sns
import matplotlib.pyplot as plt

# add another bin to dump all overflow values
# same size as the others
fixed_bin = list(np.arange(400, 455, 5))

# add another bin to dump all underflow values
# same size as the others
fixed_bin.insert(0, 395)

print(fixed_bin)

some_upper_boundary = 500

data = np.random.randint(300, high=some_upper_boundary, size=1000)

# use boolean indexing do move the data from 450 to 150000 into the
# last bin

in_first_bin = np.logical_and(data >= 0, data < 400)
in_last_bin = np.logical_and(data > 450, data <= some_upper_boundary)

data[in_first_bin] = 397
data[in_last_bin] = 447

#print(data)
ax = sns.distplot(data, bins=fixed_bin)


# Set the tick positions
ax.set_xticks(fixed_bin)

my_custom_ticklabels = list(map(str, fixed_bin))
print(my_custom_ticklabels)

my_custom_ticklabels[0] = 'under\nflow'
my_custom_ticklabels[-1] = 'over\nflow'

# Set the tick labels
ax.set_xticklabels(my_custom_ticklabels)

plt.show()

稍后我將添加一些格式:

  • 將自定義刻度 label 添加到 plot。 最后一個垃圾箱可能是“之后”。
  • 對第一個 bin 執行相同的技巧並將 label 調整為“之前”。

在此處輸入圖像描述

暫無
暫無

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

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