使用seaborn为数据框绘制直方图

10

我有一个数据框,它有多个列和许多行。许多行对于某些列没有值,在数据框中表示为NaN。以下是示例数据框:

df.head()
GEN Sample_1    Sample_2    Sample_3    Sample_4    Sample_5    Sample_6    Sample_7    Sample_8    Sample_9    Sample_10   Sample_11   Sample_12   Sample_13   Sample_14
A123    9.4697  3.19689 4.8946  8.54594 13.2568 4.93848 3.16809 NAN NAN NAN NAN NAN NAN NAN
A124    6.02592 4.0663  3.9218  2.66058 4.38232         NAN NAN NAN NAN NAN NAN NAN
A125    7.88999 2.51576 4.97483 5.8901  21.1346 5.06414 15.3094 2.68169 8.12449 NAN NAN NAN NAN NAN
A126    5.99825 10.2186 15.2986 7.53729 4.34196 8.75048 16.9358 5.52708 NAN NAN NAN NAN NAN NAN
A127    28.5014 4.86702 NAN NAN NAN NAN NAN NAN NAN NAN NAN NAN NAN NAN

我想使用Python中的Seaborn函数为这个数据框绘制直方图,因此我尝试了以下代码:
sns.set(color_codes=True)
sns.set(style="white", palette="muted")
sns.distplot(df)

但是它抛出了以下错误:
    ValueError                                Traceback (most recent call last)
    <ipython-input-80-896d7fe85ef3> in <module>()
          1 sns.set(color_codes=True)
          2 sns.set(style="white", palette="muted")
    ----> 3 sns.distplot(df)

    /anaconda3/lib/python3.4/site-packages/seaborn/distributions.py in distplot(a, bins, hist, kde, rug, fit, hist_kws, kde_kws, rug_kws, fit_kws, color, vertical, norm_hist, axlabel, label, ax)
        210         hist_color = hist_kws.pop("color", color)
        211         ax.hist(a, bins, orientation=orientation,
    --> 212                 color=hist_color, **hist_kws)
        213         if hist_color != color:
        214             hist_kws["color"] = hist_color

   /anaconda3/lib/python3.4/site-packages/matplotlib/axes/_axes.py in hist(self, x, bins, range, normed, weights, cumulative, bottom, histtype, align, orientation, rwidth, log, color, label, stacked, **kwargs)
       5627             color = mcolors.colorConverter.to_rgba_array(color)
       5628             if len(color) != nx:
    -> 5629                 raise ValueError("color kwarg must have one color per dataset")
       5630 
       5631         # We need to do to 'weights' what was done to 'x'

    ValueError: color kwarg must have one color per dataset

非常感谢任何帮助/建议,以消除这个错误..!!!


显然,一般情况下,2D数组的直方图函数映射是未定义的。正如您所看到的,distplot接受1D数组Serieslist。您可以尝试传递color=X,其中X是颜色映射的字典,例如{'Sample_1': 'Red', ...},但我严重怀疑它会起作用。 - soupault
好的,我们可以在seaborn中使用它吗?如果您能在这里分享一下就太好了。我是一个seaborn绘图的初学者。 - Alva James
我建议你避免寻找一行解决方案来解决问题。从matplotlib开始(seaborn只是在matplotlib上工作的一组高级工具)。对于你的任务,分配一个子图数组(plt.subplots(nrows=?, ncols=?)),迭代df的列并为每个subplot + column调用matplotlibhist函数。 - soupault
不清楚你的问题。你想要一个包含数据框中所有值的单个直方图吗?还是每列、每行都有一个独立的直方图?你现在提出的问题是未定义的,这就是为什么会出现错误的原因。 - mwaskom
@user1017373,你能否编辑一下这个问题吗?我只有在看到被接受的答案后才理解这个问题,但是以它目前的形式来看,你的问题非常不清楚。 - cd98
3个回答

5

我曾遇到类似的问题,因为我想在一个列(my_column)中绘制图表,但我的 pandas.DataFrame 中有 Object 类型的元素。因此,命令如下:

print(df[my_column])

给了我:

Length: 150, dtype: object

解决方案是:

sns.distplot(df[my_column].astype(float))

my_column的数据类型转换为:

Length: 150, dtype: float64

enter image description here


5

我曾经认为seaborn文档提到可以同时绘制多列,并默认按颜色突出显示。

但是在重新阅读后,我没有看到任何内容。相反,我认为我从这个教程中推断出来的,在其中一部分中,该教程绘制了一个具有多列的数据框。


然而,这个“解决方案”很简单,希望正是你所需要的:

sns.set(color_codes=True)
sns.set(style="white", palette="muted")
sns.distplot(df)

for col_id in df.columns:
    sns.distplot(df[col_id])

默认情况下,这将更改颜色,“知道”已经使用过的颜色。

Generated image from code above (using different data set)

注意:我使用了不同的数据集,因为我不确定如何重新创建你的数据集。

4
假设我已经获得了你展示的数据摘录(唯一的区别是在我的计算机上,NANNaN)。
那么,我能想到的最佳图形表现是分组条形图:每个样本为一组,在每个组内部有基因条形图(有些人偶尔称其为直方图)。
为了实现这一点,您需要首先在 R 术语中“melt”您的数据,即将其变成“长”的。然后,您可以继续进行绘图。
data = df.set_index('GEN').unstack().reset_index()
data.columns = ['sample','GEN', 'value']

sns.set(style="white")
g = sns.factorplot(x='sample'
                   ,y= 'value'
                   ,hue='GEN'
                   ,data=data
                   ,kind='bar'
                   ,aspect=2
                   )
g.set_xticklabels(rotation=30);

这里输入图片描述

如果这是您需要的类型,请告诉我们。


我正在寻找直方图来绘制分布,不过还是谢谢。 - Alva James

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接