如何在xaxis结尾设置我的xlabel

2024-04-19 12:32:29 发布

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

我要我的x轴有这样的标签格式

0 1 2 3 4 5 Xlabel

但我尝试下面的代码,结果是2行

self.axes.set_xticks(np.arange(0,6,1))
self.axes.set_xlabel('Xlabel', fontsize=9,x=1,y=1)

=>;我的结果:(

0 1 2 3 4 5 
        Xlabel 

Tags: 代码gtself格式np标签setaxes
3条回答

除了@Yann已经说过的,使用annotate来实现这一点实际上更容易。缩放/平移时,它也将保持在正确的位置。

import matplotlib.pyplot as plt
import matplotlib as mpl

ticklabelpad = mpl.rcParams['xtick.major.pad']

fig, ax = plt.subplots()
ax.set_xlim([0, 5])

# Add the label as annotation. The "5" is the padding betweent the right side
# of the axis and the label...
ax.annotate('XLabel', xy=(1,0), xytext=(5, -ticklabelpad), ha='left', va='top',
            xycoords='axes fraction', textcoords='offset points')

plt.show()

enter image description here

设置xlabel时,x参数以轴为单位指定位置,因此0是原点,1是绘图的右边缘。y被忽略,因为它应该是一个默认值,刚好在记号下面。

要覆盖此行为,可以使用Axisset_label_coordsmethod以轴单位设置位置。也可以通过提供转换来使用其他单位。

下面是一个例子:

import matplotlib.pyplot as plt
import numpy as np

ax = plt.gca()
ax.set_xticks(np.arange(0,6,1))
label = ax.set_xlabel('Xlabel', fontsize = 9)
ax.xaxis.set_label_coords(1.05, -0.025)

plt.savefig('labelAtEnd.png')
plt.show()

导致: enter image description here

选择x值(1.05)将标签放置在轴框架外部。选择y值(-0.025)作为对所需位置的最佳猜测。使用转换,可以自动将文本与Tick标签对齐。

编辑:

下面是一个使用转换的扩展示例。使用最后一个ticklabel的转换并不一定更有帮助,因为它不考虑文本的大小和对齐方式。所以为了获得某种想要的效果,我必须1)对我的x标签使用相同的字体大小,2)将垂直对齐(va)定位到“顶部”,3)将水平对齐定位到“左侧”。每个刻度的变换设置为x的数据单位(因为它是x轴)和y的轴单位(0到1),但由x轴的固定填充(以像素为单位)替换。

import matplotlib.pyplot as plt
import numpy as np

ax = plt.gca()
ax.set_xticks(np.arange(0,6,1))
ax.set_yticks(np.arange(0,6,1))
label = ax.set_xlabel('xlabel', ha='left', va = 'top', )#fontsize = 9)

# need to draw the figure first to position the tick labels
fig = plt.gcf()
fig.draw(fig.canvas.get_renderer())

# get a tick and will position things next to the last one
ticklab = ax.xaxis.get_ticklabels()[0]
trans = ticklab.get_transform()
ax.xaxis.set_label_coords(5.1, 0, transform=trans)

plt.savefig('labelAtEnd2.png')
plt.show()

这将导致:

enter image description here

这是我使用@JoeKington方法的变体。 我将最后一个刻度标签更改为轴名称。首先,我将最后一个记号设置为空字符串,然后使用annotate()。我使用annotate()是因为我需要控制axis标签的字体大小。

import numpy as np
import matplotlib.pyplot as plt

plt.xlim(50, 70)
plt.ylim(100, 250)

ax = plt.gca()
# clears last tick label
xticks = ax.get_xticks().tolist()
xticks[-1] = ''
ax.set_xticklabels(xticks)
yticks = ax.get_yticks().tolist()
yticks[-1] = ''
ax.set_yticklabels(yticks)
# sets axes labels on both ends
ax.annotate('$t$', xy=(0.98, 0), ha='left', va='top', xycoords='axes fraction', fontsize=20)
ax.annotate('$x$', xy=(0, 1), xytext=(-15,2), ha='left', va='top', xycoords='axes fraction', textcoords='offset points', fontsize=20)

plt.show(block=True)

也许有人知道更优雅的方法,因为这是可笑的复杂操作。

enter image description here

相关问题 更多 >