【发布时间】:2018-03-20 07:12:59
【问题描述】:
在动态设置刻度的情况下(如以下示例),如何更改刻度标签properties(如size、rotation 等)?我试过ax.set_xticklabels(ax.get_xticklabels(), rotation=90, size=7, ha='center'),它不起作用。实际上,ax.get_xticklabels() 甚至没有返回 5 中设置的正确数量的刻度标签 MaxNLocator - 这是一个错误吗?
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)
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)
在答案here,plt.xticks 可以做的工作。但是,我想知道是否有任何方法可以使用面向对象的接口?因为我不想用plt.xticks 全局设置这些属性。
【问题讨论】:
-
面向对象的方法是
for t in ax.get_xticklabels(): t.set_rotation(90)。由于这个答案已经在this question 中给出,我实际上认为它是重复的。也许您想编辑问题以说明在多大程度上不能解决问题?! -
@ImportanceOfBeingErnest 它绝对不是重复的,正如本页多个地方所指出的那样。如果没有设置刻度标签,
ax.get_xticklabels()将不起作用。您引用问题的替代解决方案确实有效..
标签: python matplotlib