How to set space between the axis and the label

Question:

My code:

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

The above code gives:

enter image description here

My Question:

So as you have saw the above plot the ylabel ‘Y’ is touching with the y-axis and there is space between the xlabel ‘X’ and x-axis

How can I set space between the axis and the label(like there is a space between xlabel and x-axis)?

My attempt:

In the above code I commented set_ylabel() method and tried text() method

#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

Expected output:

enter image description here

Asked By: Anurag Dabas

||

Answers:

You can set bounding by using labelpad argument like this

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

also you can add space after ‘Y ‘ label in set_ylabel line as following

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

Note:

As you mentioned you want the same spaces between both axis labels so you can set ‘X’ label using:

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

and

‘Y’ label using:

 ax.text(-(max(x)/10), max(y)/2,'Y')
Answered By: Zalak Bhalani

If you adjust the horizontal position of the label, you will have the same space as usual.

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

If you need more space, you can use the following settings.

ax.yaxis.labelpad = 20
Answered By: r-beginners
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.