如何使用 matplotlib 的 hist() 函数绘制“binned data”的图形

How to plot the graph using hist() function of matplotlib for "binned data"

提问人:user19888430 提问时间:7/20/2023 最后编辑:user19888430 更新时间:7/21/2023 访问量:45

问:

我是matplotlib的新手。我有数据分箱数据。

         Level              Quantity
0      (199.533, 271.74]  (10.213, 39.4]
1      (199.533, 271.74]  (10.213, 39.4]
2      (54.903, 127.327]  (10.213, 39.4]
3     (127.327, 199.533]  (10.213, 39.4]
4     (127.327, 199.533]  (10.213, 39.4]
...                  ...             ...
5105   (54.903, 127.327]  (10.213, 39.4]
5106   (54.903, 127.327]    (39.4, 68.5]
5107   (54.903, 127.327]  (10.213, 39.4]
5108  (127.327, 199.533]  (10.213, 39.4]
5109   (54.903, 127.327]  (10.213, 39.4]

我想为每个“等宽”的箱制作 2 个名为“水平”和“数量”的直方图。 我试过了

import pandas as pd
import matplotlib.pyplot as plt

# Sample binned data for the two variables (Level and Quantity)
data = {
    'Level': ['(199.533, 271.74]', '(199.533, 271.74]', '(54.903, 127.327]', '(127.327, 199.533]', '(127.327, 199.533]'],......
    'Quantity': ['(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]', '(10.213, 39.4]'],......
}

df_binned = pd.DataFrame(data)


plt.hist([df_binned['Level'], df_binned['Quantity']], bins=10, edgecolor='black', alpha=0.7, label=df_binned.columns)
plt.legend()
plt.title('Stacked Histograms of Binned Variables')
plt.xlabel('Bins')
plt.ylabel('Frequency')
plt.show()

它没有读取函数中的 binplt.hist()

df_binned['级别']

df_binned['数量']

我如何绘制分箱数据? 如何准备制作直方图的数据?

python matplotlib 直方图 分箱

评论

1赞 BigBen 7/20/2023
首先,使用 ,而不是 绘制分箱数据。barhist
0赞 Trenton McKinney 7/20/2023
直方图适用于原始数据点,而不是合并数据。
0赞 user19888430 7/20/2023
你是对的“直方图在原始数据点上工作,而不是分箱数据”。现在的问题是我们应该如何为直方图准备分箱数据?

答:

0赞 user19888430 7/21/2023 #1

需要数据准备

df_binned = pd.DataFrame(data)
df_binned['Level']   = df_binned['Level'].dtype(str)
df_binned['Quantity']=df_binned['Quantity'].dtype(str)

评论

0赞 Community 7/23/2023
您的答案可以通过其他支持信息进行改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。