matplotlib_basic_设置坐标轴2

本文介绍如何移动matplotlib 中 axis 坐标轴的位置,使用.spines设置边框:x轴,y轴;使用.set_position设置边框位置:x=0,y=0的位置;使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置;使用.yaxis.set_ticks_position设置y坐标刻度数字或名称的位置


Demo.py

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))

new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])

ax = plt.gca()#使用plt.gca获取当前坐标轴信息
ax.spines['right'].set_color('none')#使用.spines设置边框:右侧边框;使用.set_color设置边框颜色:默认白色
ax.spines['top'].set_color('none')#使用.spines设置边框:上边框;使用.set_color设置边框颜色:默认白色

plt.show()#figure1
ax.xaxis.set_ticks_position('bottom')#使用.xaxis.set_ticks_position设置x坐标刻度数字或名称的位置:bottom.(所有位置:top,bottom,both,default,none)
ax.spines['bottom'].set_position(('data', 0))#使用.spines设置边框:x轴;使用.set_position设置边框位置:y=0的位置;(位置所有属性:outward,axes,data)
plt.show()#figure2

ax.yaxis.set_ticks_position('left')#使用.yaxis.set_ticks_position设置y坐标刻度数字或名称的位置:left.(所有位置:left,right,both,default,none)
ax.spines['left'].set_position(('data',0))#使用.spines设置边框:y轴;使用.set_position设置边框位置:x=0的位置;(位置所有属性:outward,axes,data)
plt.show()#figure3


结果:

matplotlib_basic_设置坐标轴2_第1张图片
Paste_Image.png
matplotlib_basic_设置坐标轴2_第2张图片
Paste_Image.png
matplotlib_basic_设置坐标轴2_第3张图片
Paste_Image.png

你可能感兴趣的:(matplotlib_basic_设置坐标轴2)