【问题标题】:How to plot every column of data against every other column of data如何将每一列数据与其他每一列数据进行对比
【发布时间】:2018-10-11 17:49:03
【问题描述】:

我有一个包含 n 列和 x 行数的数据文件。 如何将每一列与其他每一列数据进行对比?

data=[]
inFile = open('random.data','r')
    for line in inFile.readlines():
        line = line.split()
        b = np.array([line],dtype=float)
        for i in range(len(b)):
            c=(b[i])
            data.append(c)
inFile.close()

这会产生一个数组,我可以在其中索引每一列,如下所示:

datax = ([i[0] for i in data])
datay = ([i[1] for i in data])
dataz = ([i[2] for i in data])
dataa = ([i[3] for i in data])

然后互相勾结:

plt.plot(datax,datay,dataz,dataa,'o')

如何使用 for 循环执行此操作,以便它适用于 n 列?

【问题讨论】:

标签: python numpy for-loop matplotlib file-io


【解决方案1】:

假设您上面的代码中的data 是pandas df,下面的代码将起作用:

import matplotlib.pyplot as plt
df_data = data
for i in range(len(df_data.columns)):
    for j in range(len(df_data.columns)):
        x = df_data.iloc[:,df_data.index[i]]
        y=  df_data.iloc[:,df_data.index[j]]
        plt.figure()
        plt.plot(x[i],y[j])

要将数据读取到 df,代码如下:

data = pd.read_csv('random.data', sep=" ", header=None) #sep depends on your file, it can be space, semicolon or anything.
data.columns = ["a", "b","c", ... "etc.", ...] # Put names of your column in place of a,b,c etc.

【讨论】:

  • 嘿 Rahul,我也不确定如何将其转换为 df。如果您知道任何好的文档,那就太好了。
  • @TomRichmond:更新了我关于如何将文件转换为 df 的答案。
  • 我还希望该图适用于任意数量的无标题列。我可以将 data.column 替换为根据文件中的列数创建的数组吗?
  • 是的...您可以用列列表替换
【解决方案2】:

您有n 列,我假设您可以通过data[] 访问每一列。

试试这个

# define n here

numberofplots = math.factorial(n)/(math.factorial(2)*math.factorial(n-2))

fig = plt.figure()
for i in range(n-1):
    for j in range(i+1,n):
        ax = fig.add_subplot(numberofplots,1, ((i+1)*j)
        ax.plot(data[i], data[j])

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 2019-04-06
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多