无法在matplotlib中更改tick标签属性

时间:2013-07-17 11:07:19

标签: python matplotlib

无论我似乎做了什么,或者我过去常常查到哪些问题 - 我似乎都无法改变刻度标签的简单属性。

此代码:

from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib.transforms import BlendedGenericTransform
import matplotlib.pyplot as plt
import numpy

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    # thicken the axis lines
    ax.axhline(linewidth=1.7, color="k")
    ax.axvline(linewidth=1.7, color="k")

    plt.xticks([-numpy.pi/2, -numpy.pi/4, 0, numpy.pi/4, numpy.pi/2], [r'$-\pi$', r'$-\pi/2$', r'$O$', r'$\pi/2$', r'$\pi$'], rotation=30)
    plt.yticks([])
    #ax.set_xticklabels([r'$-\pi$', r'$-\pi/2$', r'$0$', r'$\pi/2$', r'$\pi$'], rotation=40, ha='left')

    # end-of-axis arrows
    ax.text(0, 1.05, r'$y$', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1.03, 0, r'$x$', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

    plt.ylim(-5, 5)
    plt.xlim(-numpy.pi/2, numpy.pi/2)
    x_width = (abs(plt.xlim()[0]) + abs(plt.xlim()[1])) / 2
    y_width = (abs(plt.ylim()[0]) + abs(plt.ylim()[1])) / 2

    # end-of-axis arrows
    plt.arrow(plt.xlim()[1], -0.003, x_width*0.01, 0,
              width=x_width*0.0015, color="k", clip_on=False,
              head_width=y_width*0.24/7, head_length=x_width*0.024)
    plt.arrow(0.003, plt.ylim()[1], 0, y_width*0.01,
              width=y_width*0.0015, color="k", clip_on=False,
              head_width=x_width*0.24/7, head_length=y_width*0.024)

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_visible(True)

    for direction in ["left", "right", "bottom", "top"]:
        ax.axis[direction].set_visible(False)

    x = numpy.linspace(-numpy.pi/2, numpy.pi/2, 2500)

    yy = numpy.tan(2*(x - numpy.pi/2))
    threshold = 1000
    yy[yy > threshold] = numpy.inf
    yy[yy < -threshold] = numpy.inf

    ax.plot(x, yy, linewidth=1.2, color="black")
    ax.axvline(x=-3*numpy.pi/4, linewidth=1.0, color="k", linestyle="--")
    ax.axvline(x=-numpy.pi/4, linewidth=1.0, color="k", linestyle="--")
    ax.axvline(x=numpy.pi/4, linewidth=1.0, color="k", linestyle="--")
    ax.axvline(x=3*numpy.pi/4, linewidth=1.0, color="k", linestyle="--")

    plt.savefig('MC6.png')

特别注意这一行:

        plt.xticks([-numpy.pi/2, -numpy.pi/4, 0, numpy.pi/4, numpy.pi/2], [r'$-\pi$', r'$-\pi/2$', r'$O$', r'$\pi/2$', r'$\pi$'], rotation=30)

将标签旋转30度。同样,如果我做其他变通方法来改变字体大小,标签总是保持不变。

我是否遗漏了一些关于matplotlib的简单内容???

1 个答案:

答案 0 :(得分:3)

添加以下行:

ax.axis["xzero"].major_ticklabels.set_rotation(30) 

作为参考,这是一个邮件列表项,其中包含:http://matplotlib.1069221.n5.nabble.com/rotating-x-tick-labels-bold-labels-with-axislines-toolkit-td7661.html

至于为什么你做的事没有效果,我只能猜测。一个疯狂的猜测是状态机(当你从pyplot命名空间调用函数时它在引擎盖下工作)假定plt.xticks与底部脊椎相关,你明确地设置为不可见。