matplotlib中的笛卡尔轴标签

时间:2013-07-14 13:38:49

标签: python matplotlib

我有以下代码:

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

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

    ax.axhline(linewidth=2.0, color="black")
    ax.axvline(linewidth=2.0, color="black")

    ax.set_xticks([1])
    ax.set_yticks([1])
    ax.set_xticklabels(['x'])
    ax.set_yticklabels(['y'])

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

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

    x = numpy.linspace(-0.5, 1., 100)
    ax.plot(x, numpy.sin(x*numpy.pi), linewidth=2.0)

    plt.show()

生成此图表:

graph

两件事:

  1. “y”标签位于其侧面 - 如何使其垂直?
  2. “x”和“y”标签都不在轴线上 - 我希望它们直接出现在轴箭头之后。

1 个答案:

答案 0 :(得分:4)

实现此目的的一种简单方法是使用Axes的{​​{3}}或text方法,使用kwarg transform

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

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

ax.axhline(linewidth=2.0, color="black")
ax.axvline(linewidth=2.0, color="black")

ax.set_xticks([])
ax.set_yticks([])

ax.text(0, 1.05, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
ax.text(1.05, 0, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

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

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

x = numpy.linspace(-0.5, 1., 100)
ax.plot(x, numpy.sin(x*numpy.pi), linewidth=2.0)

plt.show()

enter image description here