简体   繁体   English

遍历列以使用Python中的单独图

[英]Iterating through columns for separate plots in Python

I am extremely new to coding, so I appreciate any help I can get. 我对编码非常陌生,因此,我感谢能获得的任何帮助。 I have a large data file that I want to create multiple plots for where the first column is the x axis for all of them. 我有一个很大的数据文件,我想创建多个图,其中第一列是所有图的x轴。 The code would ideally then iterate through all the columns with each respectively being the new y axis. 理想情况下,代码将遍历所有列,每个列分别是新的y轴。 I included my code for the individual plots, but want to create a loop to do it for all the columns. 我包括了各个图的代码,但想创建一个循环以对所有列执行此操作。

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

X = df[:,0]
col_1= df[:,1]
plt.plot(X,col_1)
plt.show()

col_2= df[:,2]
plt.plot(X,col_2)
plt.show()

Pandas will iterate over all the columns for you. 熊猫将为您遍历所有列。 Simply place the x column in the index and then just make a call to plot with your dataframe. 只需将x列放在索引中,然后调用即可使用数据框进行绘图。 Pandas uses the index as the x-axis There is no need to directly use matplotlib. 熊猫使用索引作为x轴。无需直接使用matplotlib。 Here is some fake data with a plot: 这是一些带有图的假数据:

df = pd.DataFrame(np.random.rand(10,5), columns=['x', 'y1', 'y2', 'y3', 'y4'])
df = df.sort_values('x')

          x        y1        y2        y3        y4
9  0.262202  0.417279  0.075722  0.547804  0.599150
5  0.314894  0.611873  0.880390  0.282140  0.513770
8  0.406541  0.933734  0.879495  0.500626  0.527526
2  0.407636  0.550611  0.646449  0.635693  0.807088
1  0.437580  0.194937  0.501611  0.949575  0.409130
4  0.497347  0.443345  0.658259  0.457635  0.851847
3  0.500726  0.569175  0.304910  0.151071  0.678991
6  0.547433  0.512125  0.539995  0.701858  0.358552
0  0.783461  0.649381  0.320577  0.107062  0.840443
7  0.793702  0.951807  0.938635  0.526010  0.098321

df.set_index('x').plot(subplots=True)

在此处输入图片说明

You could loop through each column plotting it on its own subplot like so: 您可以遍历每一列,将其绘制在自己的子图中,如下所示:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(df.shape[1]-1, sharex=True)
for i in range(df.shape[1]-1):
    ax[i].plot(df[:,0], df[:,i+1])

plt.show()

edit 编辑

I just realized your example was displaying 1 plot at a time. 我刚刚意识到您的示例一次显示1个图。 You could accomplish that like this: 您可以这样完成:

import matplotlib.pyplot as plt

for i in range(df.shape[1]-1):
    plt.plot(df[:,0], df[:,i+1])
    plt.show()
    plt.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM