如何在xaxis的末尾设置我的xlabel [英] How to set my xlabel at the end of xaxis

查看:23
本文介绍了如何在xaxis的末尾设置我的xlabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的x轴具有这种格式的标签

I want my x axis has the label like this format

0 1 2 3 4 5 Xlabel

但是我尝试下面的代码将我分成两行

but I try code below it result me in 2 lines

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 

推荐答案

设置xlabel时, x 参数以轴单位指定位置,因此0为原点,1为右边缘的情节. y 被忽略,因为它是默认值,位于刻度线的正下方.

When setting the xlabel, the x parameter assigns the position in axis units, so 0 is the origin and 1 is the right edge of the plot. y is ignored as it's expected to be a default value, just below the tick marks.

要覆盖此行为,您可以使用 Axis set_label_coords

To override this behavior, you can set the position in axis units using the Axis set_label_coords method. You can use other units by also providing a transform.

这是一个例子:

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()

导致:

选择 x 值 (1.05) 来将标签定位在 Axes 框架之外.选择y值(-0.025)作为对所需位置的最佳猜测.使用转换,可以根据 Tick 标签自动定位文本.

The x value (1.05) was chosen to position the label outside the Axes frame. The y value (-0.025) was chose as a best guess to the position you desired. Using a transform, it might be possible to automatically position the text in line with the Tick labels.

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

Here's an extended example using a transform. It is not necissarily more helpful to use the last ticklabel's transform, because it does not take into account the size of the text and how it is aligned. So to get a somewhat desired effect, I had to 1) use the same font size for my x label, 2) position the vertical alignment (va) to 'top', and 3) position the horizontal alignment to 'left'. The transform for each tick is set for data units for x (because it's an xaxis) and axis units for y (0 to 1), but displaced by a fixed padding (in pixels) from the x axis.

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()

结果是:

这篇关于如何在xaxis的末尾设置我的xlabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆