【问题标题】:How to set space between the axis and the label in matplotlib如何在matplotlib中设置轴和标签之间的空间
【发布时间】:2021-07-19 00:46:35
【问题描述】:

我的代码:

#importing required libraries
import numpy as np
from matplotlib.patches import Polygon
import matplotlib.pyplot as plt


#plotting data

def func(x):
    return (x-3)*(x+2)*(3*x+5)+25
a,b=2,9
x=np.linspace(0,10,30)
y=func(x)
fig,ax=plt.subplots(1,1,dpi=135)
ax.plot(x,y,linewidth=2.5,color='c')
ix=np.linspace(a,b)
iy=func(ix)
verts=[(a,0),*zip(ix,iy),(b,0)]
poly=Polygon(verts,facecolor='0.7',edgecolor='0.9')
ax.add_patch(poly)
ax.set_ylim(bottom=0)
ax.text(6.5,150,r'$\int_a^b f(x)$',horizontalalignment='center',fontsize=15)
ax.set_xlabel('X')
ax.set_ylabel('Y',rotation=0)
ax.set_xticks((a,b))
ax.set_xticklabels(('a','b'))
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.set_yticks([])
plt.show()

以上代码给出:

我的问题:

如您所见,ylabel 'Y' 与 y 轴相接触,xlabel 'X' 和 x 轴之间有空间

如何设置坐标轴和标签之间的空间(就像 xlabel 和 x 轴之间有空间一样)?

我的尝试:

在上面的代码中我注释了set_ylabel()方法并尝试了text()方法

#ax.set_ylabel('Y',rotation=0)
fig.text(0.1,0.5,'Y')
#this code creating a little space between y label and y-axis but I want the same amount of space that is between x label an x axis

预期输出:

【问题讨论】:

    标签: python numpy matplotlib data-visualization


    【解决方案1】:

    如果你调整标签的水平位置,你将拥有和平时一样的空间。

    ax.set_ylabel('Y', rotation=0, ha='right')
    

    如果您需要更多空间,可以使用以下设置。

    ax.yaxis.labelpad = 20
    

    【讨论】:

    • 此方法可替代fig.text(0.1,0.5,'Y')...正如我在问题中提到的,我想要在 x 标签和 x 轴之间有相同数量的空间....顺便说一句,感谢您的回答 :)
    【解决方案2】:

    您可以像这样使用 labelpad 参数设置边界

    ax.set_ylabel('Y', rotation=0, labelpad=10)
    

    您也可以在 set_ylabel 行中的“Y”标签后添加空格,如下所示

    ax.set_ylabel('Y ',rotation=0)
    

    注意:

    正如您提到的,您希望两个轴标签之间有相同的空格,因此您可以使用以下方法设置 'X' 标签:

     ax.text(max(x)/2, -(max(y)/10),'X')
    

    'Y'标签使用:

     ax.text(-(max(x)/10), max(y)/2,'Y')
    

    【讨论】:

    • 正如您所提到的,您希望两个轴标签之间有相同的空格,因此您可以使用ax.text(max(x)/2, -(max(y)/10),'X') 设置“X”标签,使用ax.text(-(max(x)/10), max(y)/2,'Y') 设置“Y”标签
    • 我只是错过了set_ylabel() 方法中的labelpad 参数....既然您首先回答...所以我接受这个作为答案...再次感谢 :)
    • 您可以使用fig.text(0.1,0.5,'Y') 进行设置,但这里 X 轴的范围是 0 到 10,Y 轴的范围是 0 到大约。 3000.所以你需要分别设置0.1和0.5这两个值到X和Y轴的刻度。