John Peters
John Peters

Reputation: 1179

matplotlib: showing minor tick labels on primary x axis only

I have a generic plotting class that uses matplotlib to generate (png) plots that may have multiple y axis, but always a single (shared) x-axis that shows dates.

This is the method that deals with x axis label formatting:

def format_xaxis(self, axis, primary):
    steps = (1,2,3,4,6,12)
    step = steps[min(len(self.dates) // 1000, 5)]
    axis.set_axisbelow(True)
    axis.xaxis.grid(b=True, which='minor', color='0.90', linewidth=0.5)
    axis.xaxis.set_minor_locator(MonthLocator(bymonth=range(1,13,step)))
    axis.xaxis.set_major_locator(YearLocator())
    if primary:
        axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
        axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
    else:
        plt.setp(axis.get_xticklabels(), visible=False)

with input:

What I want (and expect from the above method) is that the only the primary axis has labels and that the major labels are month-year and the minor labels month only.

What happens is that only major labels are shown on the primary axis, minor labels are not shown at all.

If I change the last 6 lines to:

    axis.xaxis.set_major_locator(YearLocator())
    axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
    axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
    if not primary:
        plt.setp(axis.get_xticklabels(), visible=False)

then minor labels are shown on all axes.

How can I show minor x-axis tick labels on the primary x-axis only?

EDIT:

Using KevinG's suggestion on the 2nd code block works:

    axis.xaxis.set_major_locator(YearLocator())
    axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
    axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
    if not primary:
        plt.setp(axis.get_xticklabels(minor=False), visible=False)
        plt.setp(axis.get_xticklabels(minor=True), visible=False)

Upvotes: 4

Views: 5580

Answers (1)

KevinG
KevinG

Reputation: 226

I noticed that a lot of the tick label stuff has minor=False as default arguments. Without having a multiple axis plot handy right now, I can only suggest you look there. I imagine something like

if primary:
    axis.xaxis.set_major_formatter(DateFormatter(fmt='%b %y'))
    axis.xaxis.set_minor_formatter(DateFormatter(fmt='%b'))
    plt.setp(axis.get_xticklabels(minor=True), visible=True)
else:
    plt.setp(axis.get_xticklabels(), visible=False)

should have some effect.

Upvotes: 3

Related Questions