【问题标题】:How to rotate axis labels for minor ticks within a semilogx plot?如何在 semilogx 图中旋转次要刻度的轴标签?
【发布时间】:2018-08-18 15:40:26
【问题描述】:

在使用 matplotlib 的以下代码中,我还想旋转 x 轴的次要刻度标签。可惜都没有

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

也没有

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

有效果。如何在此设置中控制这些标签的方向?

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()

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    您必须创建绘图,然后更新次要刻度标签的属性。

    所以移动下面的代码

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

    情节创建代码下方

    axes.semilogx(t, sinus)
    

    这是你必须做的事情的顺序:

    • 创建数据
    • 创建情节
    • 修改绘图属性

    【讨论】:

    • 我试过了,仍然不是所有的小刻度都被旋转了。
    • 也移动plt.xticks(rotation=90) 代码。您应该创建绘图然后修改属性。
    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2020-02-28
    • 2015-05-04
    • 2018-07-15
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多