【问题标题】:Scatter plot from multiple columns of a pandas dataframe来自熊猫数据框多列的散点图
【发布时间】:2017-07-18 00:03:21
【问题描述】:

我有一个如下所示的 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))

【问题讨论】:

  • y = colnames[1:] 指的是列名列表,而不是里面的数据。

标签: python pandas matplotlib


【解决方案1】:

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

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

现在的问题是您无法使用 pandas 中的散点图包装器一次绘制多个列。根据使用散点图的原因,您可能会决定使用折线图,而不是使用折线图。 IE。您可以在绘图中指定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()

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

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()

【讨论】:

    猜你喜欢
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2017-05-16
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    相关资源
    最近更新 更多