来自pandas数据帧的多个列的散点图

时间:2017-07-17 14:56:01

标签: python pandas matplotlib

我有一个pandas数据框,如下所示:

    Filename    GalCer(18:1/12:0)_IS    GalCer(d18:1/16:0)  GalCer(d18:1/18:0)  

0   A-1-1   15.0    1.299366    40.662458   0.242658    6.891069    0.180315    

1   A-1-2   15.0    1.341638    50.237734   0.270351    8.367316    0.233468    

2   A-1-3   15.0    1.583500    47.039423   0.241681    7.902761    0.201153    

3   A-1-4   15.0    1.635365    53.139610   0.322680    9.578195    0.345681    

4   B-1-10  15.0    2.370330    80.209846   0.463770    13.729810   0.395355

我正在尝试使用第一列"文件名"绘制带有共享x轴的散点子图。在x轴上。虽然我能够生成条形图,但以下代码给出了散点图的关键错误:

import matplotlib.pyplot as plt
colnames = list (qqq.columns)

qqq.plot.scatter(x=qqq.Filename, y=colnames[1:], legend=False, subplots = True, sharex = True, figsize = (10,50))

KeyError: "['A-1-1' 'A-1-2' 'A-1-3' 'A-1-4' 'B-1-10' ] not in index"

下面的条形码代码工作正常。我是否需要为散点图指定不同的内容?

import matplotlib.pyplot as plt
colnames = list (qqq.columns)
qqq.plot(x=qqq.Filename, y=colnames[1:], kind = 'bar', legend=False, subplots = True, sharex = True, figsize = (10,30))

1 个答案:

答案 0 :(得分:2)

散点图将需要两个轴的数值。在这种情况下,您可以将索引用作x值,

df.reset_index().plot(x="index", y="other column")

现在的问题是,您无法使用pandas中的散点图包装器一次绘制多个列。根据使用散点图的原因,您可能决定使用线图而不是线。即您可以为图表指定linestyle="none"marker="o",以便在图表上显示点。

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

fn = ["{}_{}".format(i,j) for i in list("ABCD") for j in range(4)]
df = pd.DataFrame(np.random.rand(len(fn), 4), columns=list("ZXYQ"))
df.insert(0,"Filename",pd.Series(fn))

colnames = list (df.columns)
df.reset_index().plot(x="index", y=colnames[1:], kind = 'line', legend=False, 
                 subplots = True, sharex = True, figsize = (5.5,4), ls="none", marker="o")

plt.show()

enter image description here

如果您绝对需要散点图,则可以先创建子图网格,然后迭代列和轴,一次将一个散点图绘制到相应的轴上。

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

fn = ["{}_{}".format(i,j) for i in list("ABCD") for j in range(4)]
df = pd.DataFrame(np.random.rand(len(fn), 4), columns=list("ZXYQ"))
df.insert(0,"Filename",pd.Series(fn))

colnames = list (df.columns)
fig, axes = plt.subplots(nrows=len(colnames)-1, sharex = True,figsize = (5.5,4),)

for i, ax in enumerate(axes):
    df.reset_index().plot(x="index", y=colnames[i+1], kind = 'scatter', legend=False, 
                          ax=ax, c=colnames[i+1], cmap="inferno")

plt.show()

enter image description here