Matplotlib概念
Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。
import numpy as np
#一般来说我们会调用Matplotlib字库来作为python绘图的接口
import matplotlib.pyplot as plt
#使用这个命令则可以无需plt.show(),直接就可以显示绘图。
%matplotlib inline
画一个最简单的折线图
#图可以自适应定义的np矩阵
plt.plot([1,2,3,4,5],[1,4,9,16,25])
#设置x轴标签,fontsize设置字体大小
plt.xlabel('x',fontsize = 16)
#设置y轴标签
plt.ylabel('y')
线的自定义
线的形状
#实践一下
plt.plot([1,2,3,4,5],[1,4,9,16,25],'d')
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel',fontsize = 16)
线的颜色
#实践一下
plt.plot([1,2,3,4,5],[1,4,9,16,25],'-.',color='m')
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel',fontsize = 16)
- 还可以这样设计
#将形状和颜色同时定义y表示颜色,o表示形状
plt.plot([1,2,3,4,5],[1,4,9,16,25],'yo')
plt.xlabel('xlabel',fontsize = 16)
plt.ylabel('ylabel',fontsize = 16)
绘制多条线
#x的幂函数绘图
chen_array = np.arange(0,5,0.5)
plt.plot(chen_array,chen_array,'r--')
plt.plot(chen_array,chen_array**2,'ys')
plt.plot(chen_array,chen_array**3,'bo')
#还可以这样表示
plt.plot(chen_array,chen_array,'r--',
chen_array,chen_array**2,'ys',
chen_array,chen_array**3,'bo')
线的宽度
#定义x在-10到10之间的线
x = np.linspace(-10,10)
#三角函数
y = np.sin(x)
#linewidth设置宽度,数值越大越宽
plt.plot(x,y,linewidth = 3.0)
线的其他定义
参数 | 描述 |
---|---|
color | 线的颜色 |
linestyle | 线的形状 |
marker | 线的标注点 |
markerfacecolor | 标注点颜色 |
markersize | 标注点大小 |
linewidth | 线的宽度 |
alpha | 线的透明度 |
plt.plot(x,y,color='y',linestyle=':',marker = 'd',markerfacecolor='r',markersize = 10)
line = plt.plot(x,y)
plt.setp(line,color='r',linewidth = 2.0, alpha = 0.2)
子图
- 在一个区域里绘制多个图
# 211 表示一会要画的图是2行一列的 最后一个1表示的是子图当中的第1个图
plt.subplot(211)
plt.plot(x,y,color='r')
# 212 表示一会要画的图是2行一列的 最后一个1表示的是子图当中的第2个图
plt.subplot(212)
plt.plot(x,y,color='b')
# 121 表示一会要画的图是1行2列的 最后一个1表示的是子图当中的第1个图
plt.subplot(121)
plt.plot(x,y,color='r')
# 122 表示一会要画的图是1行2列的 最后一个1表示的是子图当中的第2个图
plt.subplot(122)
plt.plot(x,y,color='b')
plt.subplot(321)
plt.plot(x,y,color='r')
plt.subplot(326)
plt.plot(x,y,color='b')
图的注释
plt.plot(x,y,color='y',linestyle=':',marker = 'o',markerfacecolor='r',markersize = 10)
#设置轴标注
plt.xlabel('x')
plt.ylabel('y')
#设置标题
plt.title('chen_pic')
#设置点标注
plt.text(0,0,'chen')
#试用网格
plt.grid(True)
#annotate设置点标注,箭头标注xy表示指向点,xytext注释所在点;
#arrowprops设置箭头,shrink设置箭头长短,值越小越长
plt.annotate('chen',xy=(-5,0),xytext=(-2,0.3),arrowprops = dict(facecolor='brown',shrink=0.05,headlength= 20,headwidth = 20))
风格设置
#查看风格种类
plt.style.available
- 实践一下
#黑色背景
x = np.linspace(-10,10)
y = np.sin(x)
plt.style.use('dark_background')
plt.plot(x,y,'w')
#外黑内白
plt.style.use('bmh')
plt.plot(x,y)
#ggplot风格
plt.style.use('ggplot')
plt.plot(x,y)
#风格混用
plt.style.use(['ggplot','classic'])
plt.plot(x,y)
#漫画风格
plt.xkcd()
plt.plot(x,y)