如何将轴标签移动到matplotlib中的箭头附近

2024-09-27 07:21:30 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我绘制函数的代码,我需要将“X”和“Y”标签移到第一个象限,按照惯例,它们被放置在相应的箭头附近。这是怎么做到的?在

import pylab as p
import numpy as n

from mpl_toolkits.axes_grid import axislines


def cubic(x) :
    return x**3 + 6*x


def set_axes():
    fig = p.figure(1)
    ax = axislines.SubplotZero(fig, 111)
    fig.add_subplot(ax)

    for direction in ['xzero', 'yzero']:
        ax.axis[direction].set_axisline_style('->', size=2)
        ax.axis[direction].set_visible(True)

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

    ax.axis['xzero'].set_label('X')
    ax.axis['yzero'].set_label('Y')

    ax.axis['yzero'].major_ticklabels.set_axis_direction('right')
    ax.axis['yzero'].set_axislabel_direction('+')
    ax.axis['yzero'].label.set_rotation(-90)
    ax.axis['yzero'].label.set_va('center')


set_axes()

X = n.linspace(-15,15,100)
Y = cubic(X)

p.plot(X, Y)

p.xlim(-5.0, 5.0)
p.ylim(-15.0, 15.0)

p.xticks(n.linspace(-5, 5, 11, endpoint=True))
p.grid(True)

p.show()

Tags: importtruedefasfigaxlabelgrid
1条回答
网友
1楼 · 发布于 2024-09-27 07:21:30

通常,要更改一个轴的标签位置(例如ax.xaxis)的位置,可以执行axis.label.set_position(xy)。也可以只设置一个坐标,例如'轴x轴集(1) `。在

在你的情况下,应该是:

ax['xzero'].label.set_x(1)
ax['yzero'].label.set_y(1)

然而,axislines(以及axisartistaxes_grid中的任何其他内容)是一个有些过时的模块(这就是axes_grid1存在的原因)。在某些情况下,它不能正确地对事物进行子类化。所以,当我们试图设置标签的x和y位置时,没有任何变化!在


一个快速的解决方法是使用ax.annotate在箭头的末端放置标签。不过,让我们先尝试用一种不同的方式来绘制(之后,我们将回到annotate)的地方。在


现在,你最好使用新的脊椎功能来完成你想要完成的任务。在

将x轴和y轴设置为“归零”非常简单:

^{pr2}$

enter image description here

但是,我们仍然需要漂亮的箭头装饰。这有点复杂,但它只是两个调用,用适当的参数进行注释。在

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

#  Set axis spines at 0
for spine in ['left', 'bottom']:
    ax.spines[spine].set_position('zero')

# Hide the other spines...
for spine in ['right', 'top']:
    ax.spines[spine].set_color('none')

#  Decorate the spins
arrow_length = 20 # In points

# X-axis arrow
ax.annotate('', xy=(1, 0), xycoords=('axes fraction', 'data'), 
            xytext=(arrow_length, 0), textcoords='offset points',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

# Y-axis arrow
ax.annotate('', xy=(0, 1), xycoords=('data', 'axes fraction'), 
            xytext=(0, arrow_length), textcoords='offset points',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

#  Plot
ax.axis([-4, 10, -4, 10])
ax.grid()

plt.show()

enter image description here

(箭头的宽度由文本大小(或arrowprops的可选参数)控制,因此如果愿意,将size=16指定到{}会使箭头更宽一些。)


此时,最简单的方法是将“X”和“Y”标签添加为注释的一部分,不过设置它们的位置也可以。在

如果我们只传入一个label作为第一个参数而不是一个空字符串(并稍微改变一下对齐方式),我们会在箭头的末端得到漂亮的标签:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

#  Set axis spines at 0
for spine in ['left', 'bottom']:
    ax.spines[spine].set_position('zero')

# Hide the other spines...
for spine in ['right', 'top']:
    ax.spines[spine].set_color('none')

#  Decorate the spins
arrow_length = 20 # In points

# X-axis arrow
ax.annotate('X', xy=(1, 0), xycoords=('axes fraction', 'data'), 
            xytext=(arrow_length, 0), textcoords='offset points',
            ha='left', va='center',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

# Y-axis arrow
ax.annotate('Y', xy=(0, 1), xycoords=('data', 'axes fraction'), 
            xytext=(0, arrow_length), textcoords='offset points',
            ha='center', va='bottom',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

#  Plot
ax.axis([-4, 10, -4, 10])
ax.grid()

plt.show()

enter image description here

只需稍微多做一点工作(直接访问脊椎的变换),就可以generalize the use of annotate处理任何类型的脊椎对齐(例如“掉落”的脊椎等)。在

不管怎样,希望这能有所帮助。如果你愿意,你也可以get fancier with it。在

相关问题 更多 >

    热门问题