0

I want to plot date vs time graph using matplot lib. The issue I am facing is that due to access of data many lines are showing on the xaxis and I can't find a way to plot my time on xaxis cleanly with one hour gap. Say i have data in my list as string as ['6:01','6:30','7:20','7:25']. I want to divide my xaxis from 6:00 to 7:00 and the time points between them should be plotted based on time.

Note: time list is just and example I want to do this for whole 24 hour.

I tried to use ticks and many other options to complete my task but unfortunatly I am stuck at this problem. My data is in csv file.

Below is my code: def arrivalGraph():

from datetime import  datetime, timedelta
from matplotlib import pyplot as plt
from matplotlib import dates as mpl_dates

with open("Timetable2021.csv","r") as f:

    fileData  = f.readlines()
    del fileData[0]
    date = []
    train1 = []
   
    for data in fileData:
        ind = data.split(",")
        date.append(datetime.strptime(ind[0],"%d/%m/%Y").date())
        train1Time = datetime.strptime(ind[1],"%H:%M").time()
        train1.append(train1Time.strftime("%H:%M"))


    plt.style.use("seaborn")
    plt.figure(figsize = (10,10))
    plt.plot_date(train1,date)

    plt.gcf().autofmt_xdate()#gcf is get current figure - autofmt is auto format


    dateformater = mpl_dates.DateFormatter("%b ,%d %Y")
    plt.gca().xaxis.set_major_formatter(dateformater) # to format the xaxis


    plt.xlabel("Date")
    plt.ylabel("Time")
    plt.title("Train Time vs Date Schedule")
   
    plt.tight_layout()
    plt.show()

When i run the code i get the following output:

output of above code

  • This question comes up about twice a week. Suggest mark as duplicate https://stackoverflow.com/questions/48090043/matplotlib-fix-axis-too-many-dates – Jody Klymak May 01 '21 at 02:46

1 Answers1

0

Assuming that every single minute that every single minute is present in train1 (i.e. train1 = ["00:00", "00:01", "00:02", "00:03", ... , "23:59"]), you can use plt.xticks() by generating an array representing xticks with empty string on every minute which is not 0.

    unique_times = sorted(set(train1))
    xticks = ['' if time[-2:]!='00' else time for time in unique_times]

    plt.style.use("seaborn")
    plt.figure(figsize = (10,10))
    plt.plot_date(train1,date)

    plt.gcf().autofmt_xdate()#gcf is get current figure - autofmt is auto format


    dateformater = mpl_dates.DateFormatter("%b ,%d %Y")
    # I think you wanted to format the yaxis instead of xaxis
    plt.gca().yaxis.set_major_formatter(dateformater) # to format the yaxis


    plt.ylabel("Date")
    plt.xlabel("Time")
    plt.title("Train Time vs Date Schedule")

    plt.xticks(range(len(xticks)), xticks)

    plt.tight_layout()
    plt.show()

If every single minute is not in the train1 array, you have to keep train1 data as an object and generate arrays representing xticks location and values to be used as plt.xticks() parameters.

    date = []
    train1 = []

    for data in fileData:
        ind = data.split(",")
        date.append(datetime.strptime(ind[0],"%d/%m/%Y").date())
        train1Time = datetime.strptime(ind[1],"%H:%M")
        train1.append(train1Time)

    plt.style.use("seaborn")
    plt.figure(figsize = (10,10))
    plt.plot_date(train1,date)

    plt.gcf().autofmt_xdate()#gcf is get current figure - autofmt is auto format


    dateformater = mpl_dates.DateFormatter("%b ,%d %Y")
    # I think you wanted to format the y axis instead of xaxis
    plt.gca().yaxis.set_major_formatter(dateformater) # to format the yaxis

    plt.ylabel("Date")
    plt.xlabel("Time")
    plt.title("Train Time vs Date Schedule")

    ax = plt.gca()
    xticks_val = []
    xticks_loc = []
    distance = (ax.get_xticks()[-1] - ax.get_xticks()[0]) / 24

    def to_hour_str(x):
        x = str(x)
        if len(x) < 2:
            x = '0' + x
        return x + ':00'

    for h in range(25):
        xticks_val.append(to_hour_str(h))
        xticks_loc.append(ax.get_xticks()[0] + h * distance)

    plt.xticks(xticks_loc, xticks_val, rotation=90, ha='left')


    plt.tight_layout()
    plt.show()

Here's the code output using dummy data I generated myself.enter image description here

Gusti Adli
  • 1,225
  • 4
  • 13