之前一直在这个代码里看到plt.gca()的使用,但是一直没搞明白这个怎么用,今天总结一下
gca是get current axis的首字母的缩写,就是控制坐标轴的,也是比较简单的,并不是一个很复杂的函数
移动坐标轴
import matplotlib.pyplot as plt
# 这里建立的画布大小是5*5的,并不是坐标轴范围,使用“十字按钮”拖动你就懂了!
plt.figure(figsize = (5,5))
plt.plot() # 画个只有坐标系的图(因为没有传参数,所以显示空白)
ax = plt.gca()
# 获取你想要挪动的坐标轴,这里只有顶部、底部、左、右四个方向参数
ax.xaxis.set_ticks_position('bottom') # 要挪动底部的X轴,所以先目光锁定底部!
# 在这里,position位置参数有三种,这里用到了“按Y轴刻度位置挪动”
# 'data'表示按数值挪动,其后数字代表挪动到Y轴的刻度值
ax.spines['bottom'].set_position(('data',0))
plt.show()
添加直线
import matplotlib.pyplot as plt
N = 16
for i in range(N):
plt.gca().add_line(plt.Line2D((0, i), (N - i, 0), color = 'm'))
plt.axis('tight')
plt.show()
添加形状
import matplotlib.patches as patches
import matplotlib.pyplot as plt
# 圆形
shape = patches.Circle((0, 0), radius = 1., color = 'm')
plt.gca().add_patch(shape)
# 四边形
shape = patches.Rectangle((2.5, -.5), 2., 1., color = 'c')
plt.gca().add_patch(shape)
# 椭圆形
shape = patches.Ellipse((0, -2.), 2., 1., angle = 45., color = 'y')
plt.gca().add_patch(shape)
# 花状框
shape = patches.FancyBboxPatch((2.5, -2.5), 2., 1., boxstyle = 'sawtooth', color = 'b')
plt.gca().add_patch(shape)
# 显示
plt.grid(True, alpha=0.3)
plt.axis('scaled')
plt.show()
不规则图形
import numpy as np
import matplotlib.patches as patches
import matplotlib.pyplot as plt
theta = np.linspace(0, 2 * np.pi, 8)
points = np.vstack((np.cos(theta), np.sin(theta))).transpose()
plt.gca().add_patch(plt.Circle((0, 0), radius = 1., color = 'm'))
plt.gca().add_patch(plt.Polygon(points, closed=None, fill=None, lw = 3., ls = 'dashed', edgecolor = 'c'))
plt.grid(True)
plt.axis('scaled')
plt.show()
注意下面这个操作
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(4,4))
overhang = 1.0
ax.arrow(0,0,1.0,1.0, width=0.001, color="k",
head_width=0.1, head_length=0.15, overhang=overhang)
#ax.add_line((0,0),(1,0))
ax.set_yticks([-0.2,0,0.4,0.8,1.0])
ax.set_xticks([-0.2,0,0.4,0.8,1.0])
ax.set_ylabel("overhang")
ax.set_ylim(-0.3,1.2)
ax.set_ylim(-0.3,1.2)
plt.tight_layout()
plt.show()
这里是常用的fig,ax进行画图,但是我完全可以用plt.gca()来代替,不需要用fig,ax哈
import matplotlib.pyplot as plt
plt.figure(figsize=(4,4))
overhang = 1.0
plt.gca().arrow(0,0,1.0,1.0, width=0.001, color="k",
head_width=0.1, head_length=0.15, overhang=overhang)
plt.gca().set_yticks([-0.2,0,0.4,0.8,1.0])
plt.gca().set_xticks([-0.2,0,0.4,0.8,1.0])
plt.gca().set_ylabel("overhang")
plt.gca().set_ylim(-0.3,1.2)
plt.gca().set_ylim(-0.3,1.2)
plt.tight_layout()
plt.show()