如何在Python3中使用自定义的下溢/上溢箱绘制刻面直方图?

问题描述 投票:0回答:1

我有一个带有几列(区域,日期,利润)的熊猫数据框。我想要按地区和日期划分的利润直方图。但是利润栏数据的两端都有很长的尾巴,这意味着有5个利润少于10美元的计数和280483个利润在400-450美元之间的计数,然后有6个利润大于10万美元的计数。

[我想做的是创建一个带有自定义箱的直方图,以便它显示多个箱,价格为$ 400- $ 450,只有一个箱为$ 400以下,而一个箱为$ 450以上,希望直方图中的列在上方相同的宽度。

我现在所拥有的:

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之间)仍被压缩在中间,很难看到该中间部分的真实直方图。如何将两端的尾巴(下溢和上溢箱)变成两个小箱子,它们的宽度与中间的箱子的宽度相同?]

非常感谢您的帮助!

python python-3.x pandas matplotlib seaborn
1个回答
0
投票

我的第一个想法是分别进行装仓和绘图。但是我找不到matplotlib.pyplot.barseaborn.barplot报价自定义垃圾箱大小。

所以我们必须欺骗seaborn.distplotmatplotlib.pyplot.hist(其背后的功能)。

import numpy as np

import seaborn as sns
import matplotlib.pyplot as plt
# add another bin
fixed_bin = list(np.arange(400, 455, 5))
fixed_bin.insert(0, 395)
#fixed_bin.append(150000)
print(fixed_bin)

some_upper_boundary = 1500

data = np.random.randint(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)

plt.show()

enter image description here

我稍后会添加一些格式:

  • 向图添加自定义刻度标签。最后一个bin可能是“ after”。
  • 对第一个纸槽进行相同的操作,并将标签调整为'before'。
© www.soinside.com 2019 - 2024. All rights reserved.