[Python] MATPLOTLIB: How can I align my two X-axes?

Discussão em 'Python' iniciado por Stack, Fevereiro 13, 2025.

  1. Stack

    Stack Membro Participativo

    I just can't figure out how to align my two X-axes since I'm using the same xticks array for both. I want to display the date at the top and the time at the bottom axis, but the two axes are misaligned. The data I'm using is 2601 lines long.

    Here is my code:

    import numpy as np
    import matplotlib.pyplot as plt
    import time
    from datetime import datetime
    from matplotlib.ticker import MaxNLocator

    f = open("data.txt", "r")
    #data.txt data in each line
    #HistoricalData. 4001 - Time: 20191115 20:37:00, Open: 70.185, High: 70.195, Low: 70.135, Close: 70.14, Volume: -1, Count: -1, WAP: -1s

    my_list = []
    my_list_real = np.array([])
    my_list_time = np.array([])
    counter = 0
    for x in f:
    my_list.append(x)
    counter += 1
    print(counter)

    i = 0
    while i < len(my_list):
    start = my_list.find("Open")
    start += 6
    end = my_list.find(", High")
    end -= 0
    variable = my_list[start:end]
    my_list_real = np.append(my_list_real, float(variable))

    start = my_list.find("Time: ")
    start += 6
    end = start + 8

    variable_time = my_list[start:end] + " " + my_list[(end+2):(end+10)]
    datetime_object = datetime.strptime(variable_time, '%Y%m%d %X')
    my_list_time = np.append(my_list_time, datetime_object)
    i += 1

    number_array = np.arange(len(my_list_time))

    fig = plt.figure()
    ax = fig.add_subplot()

    string_array = my_list_time.astype('str')
    plt.xticks(number_array, string_array)

    ax.plot(number_array, my_list_real)

    ax.xaxis.set_major_locator(MaxNLocator(5, min_n_ticks=5))
    ax2 = ax.twiny()
    ax2.set_xticks(number_array, minor=False)
    ax2.xaxis.set_major_locator(MaxNLocator(5, min_n_ticks=5))
    ax2.set_xticklabels(string_array, fontdict=None, minor=False)
    ax2.set_xticks(np.linspace(ax2.get_xticks()[0], ax2.get_xticks()[-1], len(ax.get_xticks())))

    ax.set(xlabel='time (s)', ylabel='Price ($)',
    title='INTC')
    ax.grid()
    fig.savefig("test.png")

    plt.show()


    Here is my output:

    [​IMG]

    How could I fix this?

    Continue reading...

Compartilhe esta Página