[英]Can someone please help me make my overlapping histograms?
我有以下格式的三个数据框,其中有一列以数字格式显示年份中的月份,以及与其相邻的一列,其中包含该月份发生的项目数。 我想创建一个重叠的直方图,详细说明三个直方图之间的分布,但由于某种原因,我一直得到同样的结果!
month_box Sum Value
0 1 4812
1 2 2053
2 3 2405
3 4 2353
4 5 2427
5 6 2484
6 8 2579
7 9 2580
8 10 2497
9 11 2510
10 12 2202
我正在使用的代码如下:
sns.distplot(bex_boxdf['month_box'],kde=False,label = 'Bexley')
sns.distplot(west_boxdf['month_box'],kde=False,label = 'Westminster')
sns.distplot(gwch_boxdf['month_box'],kde=False,label = 'Greenwich')
plt.legend(prop={'size': 12})
plt.title('Crime by month')
plt.xlabel('Month')
plt.ylabel('Density')
使用@Esa 提供的数据,这里是使用 Matplotlib 的三个不同视图。
还有一个“阶梯填充”直方图类型,我没有包括在内,但根据数据的分布可能会有用:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'month_box': [1,2,3,4,5,6,7,8,9,10,11,12],
'Bexley_sum': [4812,2053,2405,2353,2427,2484,2579,2580,
2497,2510,2202,2021],
'Westminster_sum': [4712,2050,2435,2323,2487,2414,2679,2780,
2490,2110,2702,2022],
'Greenwich_sum': [4812,2053,2405,2353,2427,2484,2579,2580,
2497,2510,2202,2021],
})
data = df["Bexley_sum"], df["Westminster_sum"], df["Greenwich_sum"]
labels = ["Bexley", "Westminster", "Greenwich"]
fig, ax = plt.subplots(ncols=3, sharex=True, sharey=True)
ax[0].hist(x=data, histtype="bar",label=labels)
ax[1].hist(x=data, histtype="barstacked",label=labels)
ax[2].hist(x=data, histtype="step", label=labels)
plt.legend()
plt.show()
Matplotlib 有很多自定义选项。 参考文档可能会有用。
https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.hist.html
有时直接从数据帧或使用 matplotlib 而非 seaborn 绘图更容易。 其他时候 seaborn 更好,所以最好至少在某种程度上学习两者。
如果您首先将数据排列到一个数据框中,这是一个简单的解决方案。 您没有提供其他两个数据帧,因此我设置了一些值作为示例。
df = pd.DataFrame({'month_box': [1,2,3,4,5,6,7,8,9,10,11,12],
'Bexley_sum': [4812,2053,2405,2353,2427,2484,2579,2580,
2497,2510,2202,2021],
'Westminster_sum': [4712,2050,2435,2323,2487,2414,2679,2780,
2490,2110,2702,2022],
'Greenwich_sum': [4812,2053,2405,2353,2427,2484,2579,2580,
2497,2510,2202,2021],
})
df.plot(x='month_box', y=['Bexley_sum', 'Westminster_sum', 'Greenwich_sum'], kind='bar')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.