user8042669
user8042669

Reputation:

How to rotate axis labels for minor ticks within a semilogx plot?

Within the following code using matplotlib, I would like to rotate also the minor tick labels of the x axis. Unfortunately neither

plt.setp(axes.xaxis.get_minorticklabels(), rotation=90)

nor

for text in axes.get_xminorticklabels():
    print("text rotated")
    text.set_rotation(90)

have an effect. How can I control in this setup the orientation of these labels?

import matplotlib
matplotlib.use('TkAgg')

import matplotlib.pyplot as plt

from matplotlib.ticker import FuncFormatter

fig, axes = plt.subplots()

import numpy as np

ONE_YEAR_IN_DAYS = 365

ONE_DAY_IN_TIMESTAMP_UNITS = 86400000000000

import pandas as pd

start = pd.Timestamp('2016-07-01')
end = pd.Timestamp('2017-07-02')

t = np.linspace(start.value, end.value, 100 * ONE_YEAR_IN_DAYS)

sinus = np.sin(2 * np.pi * 1 * t / ONE_DAY_IN_TIMESTAMP_UNITS)

t = end.value - t
t = 1000 * t / ONE_DAY_IN_TIMESTAMP_UNITS

plt.xticks(rotation=90)

plt.setp(axes.xaxis.get_minorticklabels(), rotation=90)

for text in axes.get_xminorticklabels():
    print("text rotated")
    text.set_rotation(90)

axes.semilogx(t, sinus)

def method_name():
    # return lambda y, _: '{:.16g}'.format(2*y)
    return lambda y, _: '{:.16g}'.format(2*y)


for axis in [axes.xaxis, axes.yaxis]:
    formatter = FuncFormatter(method_name())
    axis.set_major_formatter(formatter)
    axis.set_minor_formatter(formatter)

plt.show()

Upvotes: 0

Views: 547

Answers (1)

Gary Kerr
Gary Kerr

Reputation: 14420

You have to create the plot then update the properties of the minor tick labels.

So move the following code

for text in axes.get_xminorticklabels():
    print("text rotated")
    text.set_rotation(90)

below the plot creation code

axes.semilogx(t, sinus)

This is the order you must do things in:

  • create data
  • create plot
  • modify plot properties

Upvotes: 1

Related Questions