[Python] Plotting date on x-axis from integers converted to dates

Discussão em 'Python' iniciado por Stack, Março 31, 2025.

  1. Stack

    Stack Membro Participativo

    [​IMG]In my python code, reproduced below, where I sought assistance here Results of Assistance with a simple python line plot, I am plotting days as integers against cumulative rainfall values. With assistance from here Convert integer to dates in python, I have been able to convert the day numbers to dates from 1st October. In my data generation, the number of days from 1st October to 31st March is taken as 183 (including leap year). In converting from integer to date, print(days) gives only 182 dates (29Feb excluded). In the plot function, I have used

    plt.plot(days, df['Mean'], color='b', label='Mean') #days being integers converted to dates.


    I get the error

    ValueError: x and y must have same first dimension, but have shapes (1,) and (183,)


    However, plotting with the function

    plt.plot(df['Date'], df['Mean'], color='b', label='Mean') #Works fine


    works fine.

    The code

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

    df = pd.read_csv('../RnOut/RAINFALL/Cumul/CHIPAT.txt')
    fig, ax = plt.subplots(figsize=(10, 10))
    x = np.array([min(df['Date']), max(df['Date'])])
    y = np.array([min(df['Mean']), max(df['Mean'])])

    #Convert day numbers to date
    #***************************
    days = {}
    for i in range(0, max(df['Date'])):
    days = (datetime.datetime(2000, 10, 1) + datetime.timedelta(days=i)).strftime("%d %b")

    ax.set_title('Cumulative Rainfall: Oct-Mar\n *****************************')
    plt.xticks(np.arange(0, max(df['Date']),step=10))
    plt.xlabel("Days From 01 Oct")
    plt.ylabel("Cumulative Rainfall (mm)")

    plt.plot(days, df['Mean'], color='b', label='Mean')
    plt.show()


    Please assist, how do I use the generated dates?

    Continue reading...

Compartilhe esta Página