Python Matplotlib绘图
安装matplotlib
pip3 install matplotlib
绘图原理
* figure 画布
* axes 坐标系,一个画布上可以有多个坐标系
* axis 坐标轴,一个坐标系中可以有多个坐标轴,一般都是二维平面坐标系,或者三维立体坐标系
* title 标题
* legend 图例
* grid 背景网格
* tick 刻度
* axis label 坐标轴名称
* tick label 刻度名称
* major tick label 主刻度标签
* minor tick label 副刻度标签
* line 线
* style 线条样式
* marker 点标记
* font 字体相关
导入matplotlib
color = 'k' #颜色为黑色
linestyle = 'dashed' # 划线(长虚线)
marker = 'o' # 带数据标记
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(10)
plt.plot(data, color = 'k', linestyle = 'dashed', marker = 'o')
plt.show()
运行结果:
建立子图
plt.subplot(121)
plt.subplot(122)
保存图片
plt.savefig('plot1.png', dpi=300)
plt.savefig('plot1.svg')
代码:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = x
plt.figure(figsize=(20, 10)) # figsize(x, y) : x*100pixels, y*100 pixels.
plt.subplot(121)
plt.ylabel('Y', fontsize = 16) # 纵轴标签
plt.xlabel('X', fontsize = 16) # 横轴标签
plt.axis([0, 8, 0, 8])
plt.title('f(x) = x', fontsize = 16) # 设置图题
plt.text(2.5, 6.5, r'f(x) = x', fontsize = 12)
plt.grid(True) # 绘制网格线
lines = plt.plot(x, y, color = 'b', linestyle = 'dashed', marker = 'o', linewidth=1.5)
plt.subplot(122)
scatter = plt.scatter(x, y, color = 'r')
plt.show()
运行结果: