基本绘图
import matplotlib.pyplot as plt
import numpy as np
##创建画布:
plt.figure()
plt.rcParams['font.sans-serif'] = 'SimHei'#用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号
##给定x的值
x=np.arange(0,2*np.pi,0.1)
y1=np.sin(x)
y2=np.cos(x)
##画图
plt.plot(x, y1, color='hotpink',linewidth=1.5, marker=',',markersize='13',linestyle=':',
markerFaceColor='r')
plt.plot(x, y2)
#线条风格linestyle #线条标记marker
|‘-‘|实线| |‘o’ 圆圈 |‘.’ 点|
|‘–’|破折线| |‘D’ 菱形 |‘s’ 正方形|
|‘-.’|点划线| |‘h’ 六边形1 |‘*’ 星号|
|‘:’|虚线| |‘H’ 六边形2 |‘d’ 小菱形|
|‘None’|什么都不画| |‘_’ 水平线 |‘v’ 一角朝下的三角形|
|‘8’ 八边形 |‘<’ 一角朝左的三角形|
|‘p’ 五边形 |‘>’ 一角朝右的三角形|
|‘,’ 像素 |‘^’ 一角朝上的三角形|
##图例标注
plt.legend(['y=sinx','y=cosx'],bbox_to_anchor=(0.6,0.95))
#bbox_to_anchor控制图例位置,bbox_to_anchor(左右,上下)
##图标题:
plt.title('line')
##图刻度:
plt.xticks([0,np.pi/2,np.pi,np.pi*1.5,2*np.pi],['0',r'$\pi/2$',r'$\pi$',r'$3\pi/2$',r'$2\pi$'])
##图的截取范围:
# plt.xlim((0,0.4))
# plt.ylim((0,0.3))
##x,y 轴的名称:
plt.xlabel('x轴')
plt.ylabel('y轴')
# 获取当前的坐标轴, gca = get current axis
ax = plt.gca()
# 设置x坐标轴为下边框
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
# 设置y坐标轴为右边框
ax.yaxis.set_ticks_position('right')
ax.spines['right'].set_position(('data',0))
##保存:注意:先保存后显示
plt.savefig('line.png')
##显示
plt.show()
子图显示
import matplotlib.pyplot as plt
import numpy as np
#创建画布:
pl = plt.figure(figsize=(8,6),dpi=80)##画布大小
plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False
##绘制第一个子图:
pl.add_subplot(2,1,1)#创建一个2行1列的子图,并开始绘制第一副图;
plt.title('lines')
plt.xlabel('X轴')
plt.ylabel('Y轴')
x = np.arange(0,np.pi*2,0.1)
plt.plot(x,x**2,marker='*',markersize=5)
plt.plot(x,x**4,marker='>',markersize=5)
plt.legend(['y=x^2','y=x^4'])
pl.add_subplot(2,1,2)#创建一个2行1列的子图,并开始绘制第二副图;
y = np.arange(0,10,0.1)
plt.title('sin/cos')
plt.xlabel('X轴')
plt.ylabel('Y轴')
plt.plot(y,np.sin(y))
plt.plot(y,np.cos(y))
plt.legend(['y=sin(x)','y=cos(x)'])
plt.show()