[Python] Matplotlib Hover Coordinates with Labelled XTicks

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    I've got a matplotlib graph with labelled X-ticks:

    [​IMG]

    The labels repeat (in case that's relevant). In the real graph, there is a multi-level X-axis with more clarification in the lower layers.

    That works fine, but I want to be able to hover the mouse and see the X-coordinate in the top-right of the graph. Whenever I set xticks to labels, I just get a blank X-coordinate:

    [​IMG]

    If I use ax.xaxis.set_major_formatter('{x:g}'), it gets rid of my labels but the cursor coordinate starts working:

    [​IMG]

    Is there any way to make the cursor location still show the X coordinate even when I have a labelled X axis?

    This also affects mplcursors: it shows the X value as empty if I click on a line between points or with the label if I click exactly on a point (whereas I'd like to see the underlying numerical X-coordinate as "A" is a bit meaningless without the context from the secondary axis):

    [​IMG]

    Source code:

    import matplotlib.pyplot as plt
    import numpy as np
    import mplcursors

    x = np.arange(0, 9)
    y = np.random.rand(*x.shape)
    labels = ['A', 'B', 'C']*3

    fig, ax = plt.subplots()
    ax.plot(x, y, 'bx-', label='random')
    ax.set_xticks(x, labels=labels)

    # This makes the coordinate display work, but gets rid of the labels:
    # ax.xaxis.set_major_formatter('{x:g}')

    mplcursors.cursor(multiple=True)

    plt.show()

    Continue reading...

Compartilhe esta Página