Matplotlib:将xaxis tick标签设置为特定的yintercept,但将xaxis和ticks设置为y=0

2024-05-05 17:06:39 发布

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

作为标题,我有多个子批次,希望x轴刻度标签显示在y=-1处(我所有的子批次都有ylimit(-1.1到1.1),而x轴直线和记号显示在y=0。我当前的修订代码如下:

while x < 10: 
    plt.add_subplot(10,1,x).yaxis.tick_right()
    plt.subplot(10,1,x).spines['bottom'].set_position('zero')
    plt.subplot(10,1,x).spines['bottom'].set_color('xkcd:light grey')
    plt.subplot(10,1,x).set_facecolor('xkcd:dark grey')
    plt.tick_params(axis='x', direction='out', labelbottom='on', color='xkcd:light grey', labelcolor='xkcd:light grey')
    plt.plot()
    plt.ylim(-1.1,1.1)

    x+=1

plt.show()

子批次的当前示例如下所示:

enter image description here


Tags: 标题plt标签xkcd直线colorgreylight
2条回答

在数据坐标中设置ticklabel位置是相当不寻常的。但还是有可能的。与this question类似,您可以使用转换来移动标签。在这里,我们首先将它们移动1个数据单位,然后应用通常的变换。在

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(42)
import matplotlib.transforms as mtrans

x = np.linspace(2013.6,2018.4)
y = np.cumsum(np.random.randn(50))/12.+0.3

ax = plt.subplot(111)
ax.yaxis.tick_right()
ax.spines['bottom'].set_position('zero')
ax.spines['bottom'].set_color('xkcd:light grey')
ax.set_facecolor('xkcd:dark grey')
ax.tick_params(axis='x', direction='out', labelbottom=True, pad=0, 
               color='xkcd:light grey', labelcolor='xkcd:light grey')
ax.plot(x,y)
ax.set_ylim(-1.1,1.1)


trans = mtrans.Affine2D().translate(0,-1.)
for t in ax.get_xticklabels():
    t.set_transform(trans + t.get_transform())

plt.tight_layout()
plt.show()

enter image description here

通常可以通过^{}设置,并指定“数据”:

plt.subplot(10,1,x).spines['bottom'].set_position(('data', -1))

data’ : place the spine at the specified data coordinate.

matplotlib.spines | set_position

相关问题 更多 >