You can use the following basic syntax to adjust axis label positions in Matplotlib:
#adjust y-axis label position ax.yaxis.set_label_coords(-.1, .5) #adjust x-axis label position ax.xaxis.set_label_coords(.5, -.1)
The following examples show how to use this syntax in practice.
Example 1: Adjust X-Axis Label Position
The following code shows how to create a plot in Matplotlib and adjust the location of the x-axis label position only:
import matplotlib.pyplot as plt #define data x = [1, 2, 3, 4, 5, 6] y = [4, 5, 8, 14, 24, 19] #create scatterplot fig, ax = plt.subplots() ax.scatter(x, y) #add axis labels ax.set_ylabel('Y-Axis Label') ax.set_xlabel('X-Axis Label') #adjust position of x-axis label ax.xaxis.set_label_coords(.9, -.1)
Note that the axis coordinate system uses (0, 0) to represent the bottom left corner of the plot, (0.5, 0.5) to represent the center, and (1, 1) to represent the top right corner.
Example 2: Adjust Y-Axis Label Position
The following code shows how to create a plot in Matplotlib and adjust the location of the y-axis label position only:
import matplotlib.pyplot as plt #define data x = [1, 2, 3, 4, 5, 6] y = [4, 5, 8, 14, 24, 19] #create scatterplot fig, ax = plt.subplots() ax.scatter(x, y) #add axis labels ax.set_ylabel('Y-Axis Label') ax.set_xlabel('X-Axis Label') #adjust position of x-axis label ax.yaxis.set_label_coords(-.1, .1)
Example 3: Adjust Both Axis Label Positions
The following code shows how to create a plot in Matplotlib and adjust the location of both axis label positions:
import matplotlib.pyplot as plt #define data x = [1, 2, 3, 4, 5, 6] y = [4, 5, 8, 14, 24, 19] #create scatterplot fig, ax = plt.subplots() ax.scatter(x, y) #add axis labels ax.set_ylabel('Y-Axis Label') ax.set_xlabel('X-Axis Label') #adjust position of both axis labels ax.yaxis.set_label_coords(-.1, .1) ax.xaxis.set_label_coords(.9, -.1)
Additional Resources
The following tutorials explain how to perform other common functions in Matplotlib:
How to Hide Axes in Matplotlib
How to Rotate Tick Labels in Matplotlib
How to Change the Number of Ticks in Matplotlib