In case of where ticks are dynamically set (like the following example), how can I change the tick label properties (like size
, rotation
, etc)? I tried ax.set_xticklabels(ax.get_xticklabels(), rotation=90, size=7, ha='center')
, it doesn't work. In fact, ax.get_xticklabels()
doesn't even return the correct number of tick labels of 5
as set in MaxNLocator
- is this a bug?
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MaxNLocator
fig, ax = plt.subplots()
xs = range(26)
ys = range(26)
labels = list('abcdefghijklmnopqrstuvwxyz')
def format_fn(tick_val, tick_pos):
if int(tick_val) in xs:
return labels[int(tick_val)]
else:
return ''
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
ax.xaxis.set_major_locator(MaxNLocator(5, integer=True))
ax.set_xticklabels(ax.get_xticklabels(), rotation=90, size=7, ha='center')
ax.plot(xs, ys)
ax.get_xticklabels()
get empty tick labels:
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter, MaxNLocator
fig, ax = plt.subplots()
xs = range(26)
ys = range(26)
labels = list('abcdefghijklmnopqrstuvwxyz')
def format_fn(tick_val, tick_pos):
if int(tick_val) in xs:
return labels[int(tick_val)]
else:
return ''
ax.xaxis.set_major_formatter(FuncFormatter(format_fn))
ax.xaxis.set_major_locator(MaxNLocator(5, integer=True))
ax.set_xticklabels(labels, rotation=90, size=7, ha='center')
ax.plot(xs, ys)
This offsets the labels by 1. It should start with a
, not b
:
In the answer here, plt.xticks
can do the work. However, I am wondering if there is any way to use the object-oriented interface? because I don't want to globally set those properties with plt.xticks
.