你可以使用以下基本语法来调整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)
下面的例子展示了如何在实践中使用这种语法:
例1:调整X轴标签位置
下面的代码显示了如何在Matplotlib中创建一个图,并只调整X轴标签位置:
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)
请注意,坐标轴系统使用**(0,0)来代表绘图的左下角,(0.5,0.5)代表中心,(1,1)**代表右上角。
例2: 调整Y轴标签位置
下面的代码显示了如何在Matplotlib中创建一个图,并且只调整Y轴标签的位置:
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)
例3:调整两个轴的标签位置
下面的代码显示了如何在Matplotlib中创建一个图,并调整两个轴的标签位置:
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)
其他资源
下面的教程解释了如何在Matplotlib中执行其他常用功能:
如何在Matplotlib中隐藏坐标轴
如何在Matplotlib中旋转刻度线标签
如何在Matplotlib中改变刻度线的数量