如何在matplotlib/seaborn中按间隔计算绘图列值?

2024-09-24 10:23:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一列值,我必须像<;0.99,1至1.99,2至3.99和4>; 我尝试了下面的代码

data = pd.cut(TPA_Data_Details['cokumn name'], bins=[-np.inf,0.99,1,1.99,2,3.99,4,np.inf])
plt.figure(figsize=(17,15))
sns.countplot(data)

但是它给出的输出是这样的enter image description here

如何从(-inf,0.99),(1,1.99),(2,3.99)和(4,inf)生成条形图


Tags: 代码nameltgtdatanppltdetails
1条回答
网友
1楼 · 发布于 2024-09-24 10:23:36

如果确实要排除部分范围,则必须自己组织直方图:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

#generate sample data
np.random.seed(123)
n=100
df = pd.DataFrame({"A": np.random.random(n)*50 - 5})

#count the numbers per bin
vals, bins = np.histogram(df["A"], bins=[-np.inf,0.99,1,1.99,2,3.99,4,np.inf])

#plot and label only every other bar
plt.bar([f"[{i}, {j})" for i, j in zip(bins[::2], bins[1::2])], vals[::2])
plt.show()

样本输出: enter image description here

最后一个bin实际上包含np.inf,但您将设法将x标签更改为[4.0, inf]

相关问题 更多 >