Как прочитать CSV-файл и построить график данных в Python: методы и примеры

Чтобы прочитать файл CSV и построить график данных в Python, вы можете использовать несколько методов. Вот несколько популярных вариантов:

  1. Использование модуля csvи библиотеки matplotlib:

    import csv
    import matplotlib.pyplot as plt
    # Read the CSV file
    with open('your_file.csv', 'r') as file:
    reader = csv.reader(file)
    data = list(reader)
    # Extract the data for plotting
    x = [row[0] for row in data]  # Assuming the first column contains x-values
    y = [row[1] for row in data]  # Assuming the second column contains y-values
    # Plot the data
    plt.plot(x, y)
    plt.xlabel('X-axis label')
    plt.ylabel('Y-axis label')
    plt.title('Title of the Plot')
    plt.show()
  2. Использование библиотеки pandasи библиотеки matplotlib:

    import pandas as pd
    import matplotlib.pyplot as plt
    # Read the CSV file using pandas
    data = pd.read_csv('your_file.csv')
    # Extract the data for plotting
    x = data['x_column_name']
    y = data['y_column_name']
    # Plot the data
    plt.plot(x, y)
    plt.xlabel('X-axis label')
    plt.ylabel('Y-axis label')
    plt.title('Title of the Plot')
    plt.show()
  3. Использование библиотеки numpyи библиотеки matplotlib:

    import numpy as np
    import matplotlib.pyplot as plt
    # Read the CSV file using numpy
    data = np.genfromtxt('your_file.csv', delimiter=',')
    # Extract the data for plotting
    x = data[:, 0]  # Assuming the first column contains x-values
    y = data[:, 1]  # Assuming the second column contains y-values
    # Plot the data
    plt.plot(x, y)
    plt.xlabel('X-axis label')
    plt.ylabel('Y-axis label')
    plt.title('Title of the Plot')
    plt.show()

Это всего лишь несколько примеров. Существуют также другие библиотеки и методы. Не стесняйтесь выбирать тот, который лучше всего соответствует вашим потребностям.