如何绘制seaborn中离散变量的分布图
How to draw distribution plot for discrete variables in seaborn
当我为离散变量绘制 displot
时,分布可能不像我想的那样。例如。
我们可以发现barplot
处有裂缝,所以kdeplot
处的曲线在y轴上是"lower"。
在我的工作中,情况更糟:
我认为这可能是因为 "width" 或 "weight" 不是每个柱状图 1。但是我没有找到任何可以证明它的参数。
我想画这样的曲线(应该更平滑)
解决这个问题的一种方法可能是调整 KDE (see the documentation for seaborn.kdeplot()
)
的 "bandwidth"
n = np.round(np.random.normal(5,2,size=(10000,)))
sns.distplot(n, kde_kws={'bw':1})
EDIT 这里有一个不同比例的条形图和 KDE
n = np.round(np.random.normal(5,2,size=(10000,)))
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
sns.distplot(n, kde=False, ax=ax1)
sns.distplot(n, hist=False, ax=ax2, kde_kws={'bw':1})
如果问题是直方图中有一些空箱,指定箱以匹配数据可能是有意义的。在这种情况下,使用 bins=np.arange(0,16)
获取数据中所有整数的 bin。
import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt
import seaborn as sns
n = np.random.randint(0,15,10000)
sns.distplot(n, bins=np.arange(0,16), hist_kws=dict(ec="k"))
plt.show()
当我为离散变量绘制 displot
时,分布可能不像我想的那样。例如。
barplot
处有裂缝,所以kdeplot
处的曲线在y轴上是"lower"。
在我的工作中,情况更糟:
我认为这可能是因为 "width" 或 "weight" 不是每个柱状图 1。但是我没有找到任何可以证明它的参数。
我想画这样的曲线(应该更平滑)
解决这个问题的一种方法可能是调整 KDE (see the documentation for seaborn.kdeplot()
)
n = np.round(np.random.normal(5,2,size=(10000,)))
sns.distplot(n, kde_kws={'bw':1})
EDIT 这里有一个不同比例的条形图和 KDE
n = np.round(np.random.normal(5,2,size=(10000,)))
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
sns.distplot(n, kde=False, ax=ax1)
sns.distplot(n, hist=False, ax=ax2, kde_kws={'bw':1})
如果问题是直方图中有一些空箱,指定箱以匹配数据可能是有意义的。在这种情况下,使用 bins=np.arange(0,16)
获取数据中所有整数的 bin。
import numpy as np; np.random.seed(1)
import matplotlib.pyplot as plt
import seaborn as sns
n = np.random.randint(0,15,10000)
sns.distplot(n, bins=np.arange(0,16), hist_kws=dict(ec="k"))
plt.show()