Matplotlib:在特定的y轴截距处设置x轴刻度标签,但在x轴和在y = 0时刻度

时间:2018-04-03 03:55:25

标签: python matplotlib

作为标题,我有多个子图,并且希望在y = -1处显示x轴刻度标签(我的所有子图都有ylimits(-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

2 个答案:

答案 0 :(得分:3)

在数据坐标中设置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

答案 1 :(得分:0)

通常可以set_position设置,并指定&#39; 数据&#39;:

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

'数据':将脊椎放置在指定的数据坐标处。

matplotlib.spines | set_position

相关问题