Matplot学习整理
- plot_straight line
- line tick
- line annotation
- kind of plot
- subplot
1 plot_straight line 等基本操作
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
y1 = 2 * x +1
y2 = x**2
# #分两个显示,可写两个 plt.figure()
# plt.figure()
# plt.plot(x, y1)
plt.figure()
plt.plot(x, y2, label='one') #每一个后面加上label 方便最后 legend 做标注
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='two') #红色、宽为1、虚线、类别2
#取值范围
plt.xlim((-1, 2))
plt.ylim((-2, 3))
#定义坐标轴名称
plt.xlabel('I am X')
plt.ylabel('I am Y')
#改变坐标轴上的点范围,或取不同的名称
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks) # ‘\’ 称为转字符 $表示好看的字体
plt.yticks([-2, -1.8, 0, 2.2, 3], ['$really\ bad$', '$bad$', '$normal$', r'$good\alpha$', r'$really\ good$'])
#移动x,y轴到想去的地方
#gca = 'get current axis'
ax = plt.gca()
ax.spines['right'].set_color('none') #右边的轴去掉
ax.spines['top'].set_color('none') #上边也去掉
ax.xaxis.set_ticks_position('bottom') #用下面的轴作为x轴
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data', 0)) #将x轴移到 y=0 的位置
ax.spines['left'].set_position(('data', 0)) #将y轴移到 x=0 的位置
#给图像加上标注
#法1:使用默认参数
plt.legend()
# #法2:使用新的参数
# l1, = plt.plot(x, y2, label='one') #要使用handels参数,就要将数据存成object形式,并且必须加上 ,
# l2, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--', label='two')
# plt.legend(handels=[l1,l2,], labels=['aaa', 'bbb'], loc='upper right')
# plt.legend(handels=[l1,], labels=['aaa',], loc='upper right') #也可以只打印出其中一条线的标注
plt.show()
最终结果:
2 line ticks
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
plt.plot(x, y, linewidth=10, zorder=1)
plt.yl