Matplotlib python 数据可视化
文章目录
视频链接
1.如何安装matplotlib
系统是基于ubuntu18.04+python3
首先安装pip3
$ sudo apt install python3-pip
$ pip3 install numpy
$ pip3 install matplotlib
2.基本用法
2.1 画函数
画y=2*x+1的曲线在区间[-1,1]上;
'''
@Description:
@version:
@Author: sunshine
@Github: https://subshine.github.io/
@Email: 2182216077@ncepu.edu.cn
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-05 11:16:56
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 50)
## y = 2 * x + 1
y=x**2
plt.plot(x, y)
plt.show()
2.2画不同的函数在一张图上
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.plot(x, y1)
plt.figure(num=3, figsize=(8, 5),)#注意这里有,不然不显示第二个曲线
plt.plot(x, y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle='--')
plt.show()
2.2 设置figure图像
'''
@Description:
@version:
@Author: sunshine
@Github: https://subshine.github.io/
@Email: 2182216077@ncepu.edu.cn
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-06 22:23:53
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))#设置x轴的范围
plt.ylim((-2, 3))#设置y轴的范围
plt.xlabel('I am x')
plt.ylabel('I am y')
#set new sticks
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
#set tick labels
plt.yticks([-2,-1.8,-1,-1.22,3],[r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])
plt.show()
2.3 坐标轴的设置
'''
@Description:
@version:
@Author: sunshine
@Github: https://subshine.github.io/
@Email: 2182216077@ncepu.edu.cn
@Date: 2020-08-05 11:11:12
@LastEditTime: 2020-08-06 22:54:26
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2 * x + 1
y2 = x ** 2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))#
plt.ylim((-2, 3))#
plt.xlabel('I am x')
plt.ylabel('I am y')
#set new sticks
new_ticks = np.linspace(-1,2,5)
print(new_ticks)
plt.xticks(new_ticks)
#set tick labels
plt.yticks([-2,-1.8,-1,-1.22,3],[r'$really\ bad$',r'$bad$',r'$normal$',r'$good$',r'$really\ good$'])
#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')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()