matplotlib adds labels to the coordinate axes at the top of the graph and the right of the graph

In Matplotlib, by default, only the bottom and left axes are labeled

1 Set the bottom axis label

ax.xaxis.set_label_position() Adjust the position of the labels by using

import matplotlib.pyplot as plt

# 创建一个图表
fig, ax = plt.subplots()

# 生成示例数据
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]

# 在底部和顶部设置坐标轴标签
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label (Bottom)')

# 在顶部坐标轴设置标签
ax.xaxis.set_label_position('top')
# 设置顶部坐标轴的刻度线,如果没有下面的代码,默认刻度标签在底部
ax.xaxis.tick_top()
# 设置顶部坐标轴的标记
ax.set_xlabel('X Label (Top)')

# 绘制数据
ax.plot(x, y)

# 显示图表
plt.show()

insert image description here

2 Set the right axis label

Likewise, by ax.yaxis.set_label_position('right')being able to set the label for the right axis
insert image description here

Guess you like

Origin blog.csdn.net/weixin_45913084/article/details/132217762