python中的matplotlib库入门

python中的matplotlib库入门

matplotlib.pyplot是绘制各类可视化图形的命令子库,相当于快捷方式

一.引入方式

import matplotlib.pyplot as plt

二.plt.plot()函数

plt.plot(x, y, format_string, **kwargs)
  • x : X轴数据,列表或数组,可选
  • y : Y轴数据,列表或数组
  • format_string : 控制曲线的格式字符串,可选
  • **kwargs : 第二组或更多(x,y,format_string)
a = np.arange(0.0,5.0,0.01)
plt.plot(a,np.sin(2*np.pi*a),'r--',a,np.cos(2*np.pi*a),a,np.sinc(a),a,np.cosh(a))
plt.show()

在这里插入图片描述

format_string

颜色字符

颜色字符 含义 颜色字符 含义
’b’ 蓝色 ’m’ 洋红色 magenta
’g’ 绿色 ’y’ 黄色
’r’ 红色 ’k’ 黑色
’c’ 青绿色 cyan ’w’ 白色

风格字符

风格字符 含义
’‐' 实线
’‐‐' 破折线
’‐.' 点划线
’:' 虚线
’ ’ ’ ' 无线条

标记字符

标记字符 含义 标记字符 含义 标记字符 含义
‘.’ 点标记 ‘1’ 下花三角标记 ‘h’ 竖六边形标记
‘,’ 像素标记(极小点) ‘2’ 上花三角标记 ‘H’ 横六边形标记
‘o’ 实心圈标记 ‘3’ 左花三角标记 ‘+’ 十字标记
‘v’ 倒三角标记 ‘4’ 右花三角标记 ‘x’ x标记
‘^’ 上三角标记 ‘s’ 实心方形标记 ‘D’ 菱形标记
‘>’ 右三角标记 ‘p’ 实心五角标记 ‘d’ 瘦菱形标记
‘<’ 左三角标记 ‘*’ 星形标记 '|' 垂直线标记

三.pyplot的绘图区域

plt.subplot(nrows, ncols, plot_number)
# 第一个参数为使用行将平面分为几个区域,
# 第二个参数为使用列将平面分为几个区域,
# 第三个参数为定位所要绘制的区域,从左上角开始向右数,

在这里插入图片描述上图即位plt.subplot(3,2,x)的示意图

def func(t):
    return np.exp(-t) * np.exp(2*np.pi*t)
a = np.arange(0.0,5.0,0.02)

plt.subplot(211)
plt.plot(a,func(a))

plt.subplot(212)
plt.plot(a,np.sinc(2*np.pi*a),'r--')
plt.show()

plot()函数,a,np.sinc(a),a,np.cosh(a),a,np.exp(a)

在这里插入图片描述

四.plotpy的文本显示

文本显示函数

函数 含义
plt.xlabel() 对X轴增加文本标签
plt.ylabel() 对Y轴增加文本标签
plt.title() 对图形整体增加文本标签
plt.text() 在任意位置增加文本
plt.annotate() 在图形中增加带箭头的注解
a = np.arange(0.0,5.0,0.01)
plt.plot(a,np.cos(2*np.pi*a),'c--')
plt.ylabel("y")
plt.xlabel("x")
plt.title(r"$y=cos(2\pi x)$")  # $ $为Latex显示方法
plt.text(2,1,r'$\mu=100$')
plt.axis([-1,7,-2,2]) 	# x与y坐标轴的极限值
plt.grid(True) # 是否有网格
plt.show()

在这里插入图片描述
plt.text(2,1,r'$\mu=100$')替换为plt.annotate(r'$\mu=100$', xy=(2,1), xytext=(3.3,1.5),arrowprops=dict(facecolor='black',shrink=0.1,width=0.5))
则会有以下效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_41179709/article/details/84777409
今日推荐