matplotlib改变坐标轴位置

ax.spines[‘top’].set_color(‘none’)隐藏上方的直线


通过set_position方法设置坐标轴的位置

默认的设置为(‘outward’,0)。
(‘axes’,0.0~1.0),若数值=0.5表示把坐标轴放在整个坐标长度的中间位置(根据比例) (‘data’,xx),根据实际数值指定坐标轴位置


下面将x,y轴移动至中间,画函数y=x的图像

# -*- coding: utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['left'].set_position(('axes', 0.5))
ax.spines['bottom'].set_position(('axes', 0.5))

x = np.linspace(-5, 5, 1000)

ax.plot(x, x)
ax.text(-4, 4, 'y=x', color='r')
ax.set_xlabel('x', horizontalalignment='right', x=1.0)
ax.set_ylabel('y', horizontalalignment='right', y=1.0, rotation=0)
plt.show()

代码


Ref: 1.matplotlib文档