【问题标题】:How to use for loop to plot in subplots in Python如何使用 for 循环在 Python 中绘制子图
【发布时间】:2021-08-02 14:35:03
【问题描述】:

输入数据示例:

我是python的初学者。我使用 for 循环读取几个 csv 文件,如下所示(所有这些文件都是相同的格式)。

到目前为止,我的代码如下所示。

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

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

ax, fig = plt.subplots(4,4,sharex=False, sharey=False, figsize=(22, 10), dpi=70, linewidth=0.5)
ax = np.array(ax)

def loop_directory(directory):
    for filename in os.listdir(directory):
        if filename.endswith(".csv"):
            file_directory = os.path.join(directory, filename)
            # print(filename)
            df = pd.read_csv(file_directory)

            df = df[df['Tavg'].isin([-999]) == False]

            df[['Year','Month']] = df[['Year','Month']].astype(int).astype(str)
            df["Year&Month"] = df[['Year', 'Month']].agg("/".join,axis=1)

            df["Year&Month"] = pd.to_datetime(df["Year&Month"])
            x = df["Year&Month"]
            y = df["Tavg"]

            for axes,col in zip(x, y):
                axes.plot(df.index, df[col]) # here is the problem, i dont know how to use for loop to plot in subplots
    plt.show()

if __name__ == "__main__":
   loop_directory(r"C:\Users\LAB312\Desktop\vietnam\anomaly")

我又尝试了十次,但都没有成功。

我想知道如何使用这些语法。斧头拉链等。

enter image description here

我想在一个情节中的每个子情节中进行情节。 它应该绘制每个斧头。

【问题讨论】:

  • 将数据采集代码和绘图代码分开。收集数据后,使用 plt 子图或参考 matplotlib 示例。
  • 你能澄清一下问题是什么吗?你检查过 matplotlib 文档吗?

标签: python python-3.x for-loop zip subplot


【解决方案1】:

首先,您的figax 在您对plt.subplots 的调用中颠倒过来,应该是:

fig, ax = plt.subplots(4,4,sharex=False, sharey=False, figsize=(22, 10), dpi=70, linewidth=0.5)

然后您可以访问每组轴以通过索引调用plot。您可以索引 4 x 4 numpy 数组,以获取在 4 x 4 网格中设置的每个轴。即ax[0, 0].plot(...)ax[0, 1].plot(...)等,直到ax[3, 3].plot(...)

您的问题需要更多信息来阐明您希望如何绘制数据!我可以看到您将前两列合并为 4 列,但请考虑您希望如何绘制每个样本。


编辑:当您想在ax[0, 0]ax[0, 1] 等中按顺序绘制文件时,您可以通过flatten the 2D numpy array of axes 获得一维迭代,您可以循环遍历或使用一个值进行索引。我没有您的文件,因此无法对其进行测试,但这里有一些演示代码,可以让您了解该怎么做。

正如 cmets 中提到的 @sam,您应该将 csv 收集逻辑和绘图逻辑分开。

def loop_directory(directory):
    # Get all files, filter for '.csv' and prepend dir path
    files = os.listdir(directory)
    csvs = [os.path.join(directory, f) for f in files if f.endswith('.csv')]
    return csvs

def plot_csvs(csvs):
    fig, ax = plt.subplots(4, 4, sharex=False, sharey=False, figsize=(22, 10), dpi=70, linewidth=0.5)
    ax = np.array(ax).flatten()  # Flatten to 1D, [0 ,0], [0, 1], etc

    # This assumes number of subplots >= number of CSVs
    for i, filename in enumerate(csvs):
        df = pd.read_csv(filename)

        # Do your processing here

        x = df["Year&Month"]
        y = df["Tavg"]

        ax[i].plot(x, y)

    plt.show()
    
csv_dir = '/path/to/csv/dir'
csv_paths = loop_directory(csv_dir)
plot_csvs(csv_paths)

【讨论】:

  • 我已经在最新版本中展示了我想要什么样的情节。你能检查一下吗谢谢。
  • @9S47L852 抱歉,您能说得更具体一点吗?在您的 4x4 网格中,您想要在每个图中做什么?我假设您想要每列与年和月(即 Precip 与年、Tmin 与年、Tmax 与年以及 Tavg 与年),但这只需要 4 个图。你想用其他 12 个子图做什么?
  • 因为我在那个文件夹中有 15 个 csv 文件,并且每个文件都有相同的列,例如 Tmax Tmin Tavg Year Month Precip,但我只需要 Year 和 Tavg。我想要 15 个 csv 文件,它们可以绘制到 15 个子图中,x 轴和 y 轴分别为 Year 和 Tavg。
  • 非常感谢,我对此很困惑,所以我的问题不太清楚。对不起
  • 我今天试了一下,成功了,非常感谢
猜你喜欢
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 2020-07-24
  • 2018-05-13
  • 2021-04-15
  • 2021-05-23
相关资源
最近更新 更多