简体   繁体   中英

MatPlotLib X axis with dates

I have a graph within a GUI which opens with a button click. It opens from a csv file that constantly updates, hence the counting at the beginning, I wanted to limit the number of entries for the x-axis.

The plot works for the four lines however, I have been unable to refine the x axis, what I would like to do is;

  1. Rotate the font
  2. Remove the trailing zeros for the dates
  3. Possibly Change the Date Format to DMY H:M

The Below script is what I have so far:

def open_graph():
    import numpy as np
    import matplotlib.pyplot as plt
    import datetime as dt 
    from dateutil import parser
    from csv import reader
    with open('Voltage_Readings.csv','r') as f:
        data = list(reader(f))

    file=open('Voltage_Readings.csv')
    numlines=(len(file.readlines())-1)
    start=numlines-100
    end=numlines

    fig=plt.figure()
    ax=plt.subplot(111)

    DTG = [parser.parse(i[1]) for i in data[start:end]]
    Battery_Level = [i[2] for i in data[start:end]]
    Gene_Supply = [i[3] for i in data[start:end]]
    Solar_Supply = [i[4] for i in data[start:end]]
    Wind_Supply = [i[5] for i in data[start:end]]

    plt.plot(DTG, Battery_Level,'-r', label='Battery')
    plt.plot(DTG, Gene_Supply,'-y', label='Gene')
    plt.plot(DTG, Solar_Supply,'-b', label='Solar')
    plt.plot(DTG, Wind_Supply,'-g', label='Wind')

    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width *0.85, box.height])
    ax.legend(bbox_to_anchor=(1, 1),loc=2)

    plt.title('VOLTAGE MEASUREMENTS FROM POWER SOURCES')
    plt.xlabel('Time')
    plt.ylabel('Voltage')

    plt.show()

I would appreciate any assistance is being able to achieve this as I am still learning.

Here is a better answer:

Just add this before your plt.show() command:

fig.autofmt_xdate()
import matplotlib.dates as mdates
ax.fmt_xdata = mdates.DateFormatter('%d-%m-%Y %H:%M')
datetimefmt = mdates.DateFormatter("%d-%m-%Y %H:%M")
ax.xaxis.set_major_formatter(datetimefmt)

Running autofmt_xdate makes the dates slanted. Setting ax.fmt_xdata sets the date format when you hover your mouse over a point. Running ax.xaxis.set_major_formatter sets the date format on the x axis.

Interestingly enough in my own matplotlib code I've done my own formatting of the dates on the x axis because I wasn't aware of these auto formatting features. I'm going to have to revise my code to use what's already in matplotlib.

Bobby

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM