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()
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()
除了@Yann已经说过的,使用
annotate
来实现这一点实际上更容易。缩放/平移时,它也将保持在正确的位置。设置xlabel时,
x
参数以轴为单位指定位置,因此0是原点,1是绘图的右边缘。y
被忽略,因为它应该是一个默认值,刚好在记号下面。要覆盖此行为,可以使用
Axis
set_label_coords
method以轴单位设置位置。也可以通过提供转换来使用其他单位。下面是一个例子:
导致:
选择x值(1.05)将标签放置在轴框架外部。选择y值(-0.025)作为对所需位置的最佳猜测。使用转换,可以自动将文本与
Tick
标签对齐。编辑:
下面是一个使用转换的扩展示例。使用最后一个ticklabel的转换并不一定更有帮助,因为它不考虑文本的大小和对齐方式。所以为了获得某种想要的效果,我必须1)对我的x标签使用相同的字体大小,2)将垂直对齐(va)定位到“顶部”,3)将水平对齐定位到“左侧”。每个刻度的变换设置为x的数据单位(因为它是x轴)和y的轴单位(0到1),但由x轴的固定填充(以像素为单位)替换。
这将导致:
这是我使用@JoeKington方法的变体。 我将最后一个刻度标签更改为轴名称。首先,我将最后一个记号设置为空字符串,然后使用annotate()。我使用annotate()是因为我需要控制axis标签的字体大小。
也许有人知道更优雅的方法,因为这是可笑的复杂操作。
相关问题 更多 >
编程相关推荐