Matplotlib简单使用

前言

Matplotlib画图基础,这个会了基本能做图。

简单绘图

引入包

import matplotlib.pyplot as plt
import numpy as np

列表绘图

只需要使用python的列表即可画图。

a=[1,2,3]
plt.plot(a)
plt.show()

image.png
这样x 轴是列表的index。
y轴是列表的值。

但是这样是不是很奇怪。因为列表的index不可能为小数的。

我们也可以用两个列表

a=[1,2,3]
b=[4,5,6]
plt.plot(a,b)
plt.show()

image.png
这样 x轴的是a列表的值。
y轴是b列表的值。
注意,a与b的size一定要相同否则会报错
例如

a=[1,2,3,4]
b=[4,5,6]
plt.plot(a,b)
plt.show()

image.png

改变线条样式

我们可能不喜欢我们的图都是一条线。那么我们可以改变自己图的样式。

改个虚线

plt.plot(a,b,'--')

image.png
默认蓝色太丑,改个颜色吧。

plt.plot(a,b,'--',color='r')

image.png

这样画是不是找不到列表的点了。那么标记一下点吧。

plt.plot(a,b,linestyle='--',color='r',marker='|')

image.png

那么matplotlib一共提供了这么多种样式。这个表转自https://www.cnblogs.com/haore147/p/3633017.html
image.png
上面的颜色那一列是不齐的。只列出了常用的颜色。下面给出所有颜色,颜色控可以记住。
转自https://www.cnblogs.com/darkknightzh/p/6117528.html

682463-20161130140039052-1274666212.png

多图

为了更好的比较,我们可以把两个图画到一个区域。

#数据
t=np.arange(0.0,2.0,0.1)
s=np.sin(t*np.pi)
#画图
plt.plot(t,s,'r--',t*2,s,'b--')
plt.show()

image.png

分不清坐标轴了怎么办。加坐标轴标签。

plt.plot(t,s,'r--',t*2,s,'b--')
plt.xlabel('this is x')
plt.ylabel('this is y')
plt.show()

image.png

分不清楚两个图是什么鬼东西了怎么办。加函数标签。

plt.plot(t,s,'r--',label='hehehe')
plt.plot(t*2,s,'b--',label='hahaha')
plt.legend()

image.png

最后干脆起个名字吧

plt.title('this is title')
plt.plot(t,s,'r--',label='hehehe',marker='*')
plt.plot(t*2,s,'b--',label='hahaha',marker='>')
plt.xlabel('this is x')
plt.ylabel('this is y')
plt.legend()

猜你喜欢

转载自blog.csdn.net/skullFang/article/details/78776124