1

There seems to be some problem with the graph i'm plotting because the x-axis ticks aren't being placed in the right places.

It appears as if there's additional x-axis tick labels being added because they're not conforming to the rules I've been giving them.

Weird x-tick labels not rotating as required

As you can see above, the major ticks (dates i.e. 2018-09-22) are offset to the left a little bit. This gives the minor ticks (hours i.e. 06:00 AM) some space.

However not all of the minor ticks follow the rotation rule.

Adjusting the x-axis ticks

Here's the code I used to label the x axis ticks:

def label_x_axis(axis, title, dates, figure):
    axis.set_title(title)

    axis.grid(True)

    axis.xaxis.set_major_locator(mdates.DayLocator())
    axis.xaxis.set_minor_locator(mdates.HourLocator(np.arange(0, 25, 6)))

    axis.set_xticklabels(dates, rotation=60, horizontalalignment='right', minor=True, fontdict=(
        {
            'fontsize': '6',
            'horizontalalignment': 'right'
        }
    ))

    axis.set_xticklabels(dates, rotation=60, horizontalalignment='right', minor=False, fontdict=(
        {
            'fontsize': '8',
            'horizontalalignment': 'right'
        }
    ))

    # Create offset transform by 5 points in x direction
    dx, dy = -12 / 72.0, 0 / 72.0

    # offset = figure.dpi_scale_trans  # matplotlib.transforms.Affine2D().translate(dx, dy).rotate(0)

    # matrix
    offset = matplotlib.transforms.ScaledTranslation(dx, dy, figure.dpi_scale_trans)

    axis.xaxis.labelpad = 20

    dayFmt = mdates.DateFormatter('%Y-%m-%d')
    hourFmt = mdates.DateFormatter('%H:%M %p')

    axis.xaxis.set_major_formatter(dayFmt)
    axis.xaxis.set_minor_formatter(hourFmt)

    # apply offset transform to all x ticklabels.
    for label in axis.xaxis.get_majorticklabels():
        label.set_transform(label.get_transform() + offset)

Full Google Colaboratory example here.

2
  • @Lucas - There is a Google Colaboratory Python runnable script at the end of the question. Is that not a sufficient MCVE? Or is that not 'minimal' enough? It's not a whole project there, it's really just the plotting code.
    – dsapalo
    Sep 25, 2018 at 5:48
  • 1
    You let matplotlib automatically choose the locations of the ticks. But you manually set the labels for those automatically chosen ticks via set_ticklabels. Never use set_ticklabels this way. In this case I do not see the reason to use it at all. Just removing it should fix the issue. Sep 25, 2018 at 11:23

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.