我想绘制直方图,但使用点而不是条形图。
x_n10_p0_6 = binom.rvs(n=10, p=0.6, size=10000, random_state=0)
x_n10_p0_8 = binom.rvs(n=10, p=0.8, size=10000, random_state=0)
x_n20_p0_8 = binom.rvs(n=20, p=0.6, size=10000, random_state=0)
df = pd.DataFrame({
'x_n10_p0_6': x_n10_p0_6,
'x_n10_p0_8': x_n10_p0_8,
'x_n20_p0_8': x_n20_p0_8
})
sns.histplot(df)
这就是我得到的:
我希望看到这样的东西:
来源:https://en.wikipedia.org/wiki/Binomial_distribution#/media/File:Binomial_distribution_pmf.svg
histplot 有一个元素属性,但它只接受值 {“bars”, “step”, “poly”}
最佳答案
您正在处理离散分布。相反,kde 图尝试通过平滑输入值来近似连续分布。因此,带有离散值的 kdeplot 只能给出您想要的图的粗略近似值。
Seaborn 的 histplot
目前仅实现离散分布的条形图。但是,您可以通过 matplotlib 模拟这样的图。这是一个例子:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
from scipy.stats import binom
import pandas as pd
import numpy as np
x_n10_p0_6 = binom.rvs(n=10, p=0.6, size=10000, random_state=0)
x_n10_p0_8 = binom.rvs(n=10, p=0.8, size=10000, random_state=0)
x_n20_p0_8 = binom.rvs(n=20, p=0.6, size=10000, random_state=0)
df = pd.DataFrame({
'x_n10_p0_6': x_n10_p0_6,
'x_n10_p0_8': x_n10_p0_8,
'x_n20_p0_8': x_n20_p0_8
})
for col in df.columns:
xmin = df[col].min()
xmax = df[col].max()
counts, _ = np.histogram(df[col], bins=np.arange(xmin - 0.5, xmax + 1, 1))
plt.scatter(range(xmin, xmax + 1), counts, label=col)
plt.legend()
plt.gca().xaxis.set_major_locator(MaxNLocator(integer=True)) # force integer ticks for discrete x-axis
plt.ylim(ymin=0)
plt.show()
请注意,seaborn 的 histplot
有比本示例中显示的更多选项(例如,将计数缩小到密度)。
关于python - 如何用点而不是条形图创建直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76894982/