首页 > 解决方案 > 来自熊猫列的多个分布图

问题描述

我正在尝试使用 Seaborn 来绘制 Pandas DataFrame 的内容,但对于我的生活,我无法弄清楚如何堆叠 distplots。我拥有的 DataFrame 看起来像这样(简化)。

Image    | Obj1 | Obj2 | ... | ObjN
-----------------------------------
img1.jpg |   2  |   1  | ... | 0
-----------------------------------
img2.jpg |   5  |   5  | ... |  5
-----------------------------------
img3.jpg |   9  |   0  | ... |  1

现在,我想做的是绘制 N 对象在整个图像集上的分布。有了这个,我想看看有多少图像中有 Obj1,有多少有 Obj2 int 等等。这纯粹是视觉上的事情,所以不要想这可能不是显示所述数据的最佳方式。

本质上,我想做的是:

for column in df.column:
   sns.distplot(column) # Stack these distributions together with different colors 

plt.show() # Display one plot with N-distribution plots inside

希望得到与此类似的输出(ish):示例图


编辑

在@con_u's answer的基础上,我生成了以下图表:

原点没有放大

尽管在图 1 中可以看到垂直条,但它们相当无用。我知道分布严重偏向于较低的数字(计数),所以也许我不走运,需要重新考虑我的绘图选项。

标签: pythonpandasseaborn

解决方案


这对我有用。

# ----------------------------------------------------------------------
# Import library
# ----------------------------------------------------------------------
import numpy as np
import pandas as pd
import seaborn as sns
import random

# ----------------------------------------------------------------------
# Create an artificial dataframe
# ----------------------------------------------------------------------
df = pd.DataFrame({'image':np.arange(100) + 1,
                  'obj1':np.random.randint(low=1, high=100, size=100),
                  'obj2':np.random.randint(low=1, high=100, size=100),
                  'obj3':np.random.randint(low=1, high=100, size=100),
                  'obj4':np.random.randint(low=1, high=100, size=100)})

df = df.set_index('image')
df.head(10)

# ----------------------------------------------------------------------
# Plot the distributions (column-wise) (if you just want some columns)
# ----------------------------------------------------------------------
sns.distplot(df[['obj1']], hist=False, rug=True)
sns.distplot(df[['obj2']], hist=False, rug=True)
sns.distplot(df[['obj3']], hist=False, rug=True)
sns.distplot(df[['obj4']], hist=False, rug=True)
sns.plt.show()

# ----------------------------------------------------------------------
# Plot the distributions (column-wise) (looping method)
# ----------------------------------------------------------------------
for col in df.columns:
  sns.distplot(df[[col]], hist=False, rug=True)

您可能还想在这里查看相关的:

在此处输入图像描述


推荐阅读