[Python] Better way to run this python (matplotlib) code for plotting and saving images

Discussão em 'Python' iniciado por Stack, Novembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I have the following code that reads data from a csv, plots it and then saves the plot as images. The csv file has x and y values in columns index 0 and 1 and also has RGB values for color in column index 18 through 21. Through this code I am able to read the x and y values at any row and plot them as a line connected to the previous x and y values in a specific color. What I get in the end is a series of images where my csv x and y values are being plotted sequentially. The issue is that this code takes a really long time to execute for csv files with about 5,000 rows. For csv files with more than 10,000 rows my system runs out of memory soon and the code fails. Any recommendations on how to make it better?

    import matplotlib.pyplot as plt
    import csv
    import os

    csv_file_path = "my_data.csv"
    output_dir = "my_dir"

    try:
    with open(csv_file_path, 'r') as file:
    reader = csv.reader(file)
    next(reader) # Skip the header

    x = []
    y = []
    colors = []

    # Create the figure and axes only once
    fig, ax = plt.subplots(dpi=300)

    # Set axis limits and aspect ratio
    ax.set_xlim(0, 960*2)
    ax.set_ylim(-960*2, 0)
    ax.set_aspect('equal', adjustable='box')
    ax.axis('off')

    for i, row in enumerate(reader):
    x.append(float(row[0]))
    y.append(-float(row[1])) # y-coordinate needs to be inverted for plotting
    rgb = tuple(float(val)/255.0 for val in row[18:21])
    colors.append(rgb)

    # Plot each line segment with its color
    if i > 0: # Start plotting from the second point
    ax.plot(x[i-1:i+1], y[i-1:i+1], linewidth=0.5, color=colors[i-1])

    # Save the figure
    frame_filename = os.path.join(output_dir, f"frame_{i:06d}.png")
    plt.savefig(frame_filename, transparent=True, bbox_inches='tight', pad_inches=0)

    plt.close(fig) # Close the figure after the loop

    print(f"Frames saved in the directory: {output_dir}")

    except FileNotFoundError:
    print(f"Error: File not found at {file_path}")
    except Exception as e:
    print(f"An error occurred: {e}")

    Continue reading...

Compartilhe esta Página