可视化元素:
画板和画布:figure and subplot
图像的元素:其中的英文需要被记住
根据需求选择图形:
- 数值类型:散点图 - scatter
- 时间序列:折线图 - line
- 分类数据:柱状图 - bar
- 颜色/地图分布:热图 - heat map
如何用python的matplotlib进行可视化:
折线图 - plot
- 定义x,y轴上的点
- 使用plot绘制线条
- 显示图形
#导入matplotlib的pyplot模块
import matplotlib.pyplot as plt
#定义x
x = [1,2,3,4]
#定义y
y = [2,4,6,8]
#绘制
plt.plot(x,y)
#显示
plt.show()
设置线条属性:
matplotlib.lines.Line2D - Matplotlib 3.3.0 documentationmatplotlib.org添加属性:
- color:颜色
- marker:点的形状
- linestyle:线条形状
设置坐标轴axis:
axis:坐标轴范围
语法为axis[xmin, xmax, ymin, ymax], 也就是axis[x轴最小值, x轴最大值, y轴最小值, y轴最大值]
#颜色紫色,点是方形,虚线
plt.plot(x, y, color='purple',marker='s',linestyle='dashed')
#plt.plot(x, y, 'plot1')
plt.axis([0, 6, 0, 10])
plt.show()
同一个图里放多个线条:
用arrange快速生成数组 arrange([start], [stop], [step] ]
import numpy as np
t = np.arange(0, 10, 0.5)
t
array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5, 5. , 5.5, 6. , 6.5, 7. , 7.5, 8. , 8.5, 9. , 9.5])
#线条1
x1=y1=t
#线条2 - t的二次方
x2=x1
y2=t**2
#线条3 t的三次方
x3=x1
y3=t**3
#使用plot绘制线条
linesList=plt.plot(x1, y1,
x2, y2,
x3, y3 )
#用setp方法可以同时设置多个线条的属性
plt.setp(linesList, color='green',linestyle = 'dashed')
plt.show()
print('返回的数据类型',type(linesList))
print('数据大小:',len(linesList))
查看数据类型和长度:
print('datatype:',type(linesList))
print('datalength:',len(linesList))
datatype: <class 'list'>
datalength: 3
所有参入的值内部都会转换为numpy的数组。
添加文本:
注释的使用:
- 参数名xy:箭头注释中箭头所在位置
- 参数名xytext:注释文本所在位置
- arrowprops在xy和xytext之间绘制箭头
- facecolor是颜色
- shrink表示注释点与注释文本之间的图标距离
#找到 matplotlib 加载的配置文件路径
import matplotlib
matplotlib.matplotlib_fname()
#定义x
x = [1,2,3,4]
#定义y
y = [2,4,6,8]
#绘制
plt.plot(x,y)
#添加文本:
#x轴文本
plt.xlabel('x_axis')
#y轴文本
plt.ylabel('y_axis')
#标题
plt.title('Header')
#添加注释
plt.annotate('Attention pls!', xy=(2,5), xytext=(2, 7),
arrowprops=dict(facecolor='red', shrink=0.01),
)
#显示
plt.show()
多图绘图:
创建画板figure
创建画纸subplot