如何在Python3中使用自定义的下溢/上溢容器绘制刻面直方图?
我有一个包含多个列(地区、日期、利润)的熊猫数据框架。我想按地区和日期列出利润柱状图。但利润列数据两边都有一条长尾,这意味着10美元以下的利润有5项,400-450美元之间的利润有280483项,然后是10万美元以上的利润有6项 我想做的是创建一个带有定制箱子的柱状图,这样它可以显示多个400-450美元的箱子,一个400美元以下的箱子,一个450美元以上的箱子,希望柱状图中的列在相同的宽度以上 我现在所拥有的:如何在Python3中使用自定义的下溢/上溢容器绘制刻面直方图?,python,python-3.x,pandas,matplotlib,seaborn,Python,Python 3.x,Pandas,Matplotlib,Seaborn,我有一个包含多个列(地区、日期、利润)的熊猫数据框架。我想按地区和日期列出利润柱状图。但利润列数据两边都有一条长尾,这意味着10美元以下的利润有5项,400-450美元之间的利润有280483项,然后是10万美元以上的利润有6项 我想做的是创建一个带有定制箱子的柱状图,这样它可以显示多个400-450美元的箱子,一个400美元以下的箱子,一个450美元以上的箱子,希望柱状图中的列在相同的宽度以上 我现在所拥有的: import numpy as np import pandas as pd im
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')
然而,这给了我一个均匀分布的X轴,从0到150000。我所有的数据(在400到450之间)仍然被挤在中间,很难看到中间部分的真实直方图。如何使两端的尾部(下溢和溢出箱)变成两个小的箱,宽度与中间的箱一样宽?
非常感谢你的帮助 我的第一个想法是分别进行装箱和绘图。 但我找不到
matplotlib.pyplot.bar
或seaborn.barplot
提供的
自定义垃圾箱大小
所以我们必须欺骗seaborn.distplot
或matplotlib.pyplot.hist
(它背后的功能)
将numpy导入为np
导入seaborn作为sns
将matplotlib.pyplot作为plt导入
#添加另一个存储箱以转储所有溢出值
#和其他的一样大
fixed_bin=列表(np.arange(400455,5))
#添加另一个箱子以转储所有下溢值
#和其他的一样大
固定箱插入件(0395)
打印(固定邮箱)
某些上边界=500
data=np.random.randint(300,高=一些上边界,大小=1000)
#使用布尔索引将数据从450移动到150000
#最后一箱
在逻辑上(数据>=0,数据<400)
在逻辑上,你是指非等距的箱子吗?是的,基本上我希望我的箱子是(0400),(400410),(410420),(420430),(430440),(440450),(450150000)。但是当它们显示为直方图条时,我希望每个条表示每个箱子中的计数宽度相等。因此,X轴将缩放到我的箱子,而不是正常的0到150000比例。看看numpy和scipy的组织图函数,我认为它们支持这些箱子。正如您已经做的那样,您可以手动调整尾部。我的问题不是wi正如你所看到的,我已经用numpy做了箱子。问题是箱子在X轴上正确显示的宽度相同(比如尺寸2),而不是数学宽度(150000)。请编辑你的代码,df
缺失,
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()