1 Matplotlib-介绍
- Matplotlib是一个强大的Python绘图和数据可视化的工具包。
- 安装方法:pip install matplotlib
- 引用方法: import matplotlib.pyplot as plt
- 绘图函数:plt.plot()
- 显示函数:plt.show()
import matplotlib.pyplot as plt
1.1 Plot-简单使用
plt.plot() # 画图,主要是折线图
plt.show() # 展示图形
plt.plot([1, 2, 3, 4], [2, 3, 1, 7]) # 两个参数,x和y,可以是列表,也可以是numpy的array
plt.show()
plt.plot([1, 2, 3, 4], [2, 3, 1, 7], 'o-') #“o”代表点,“-”代表线
plt.show()
- plot函数:绘制折线图
- 线型linestyle(-,-.,–,:)
- 点型marker(v.^,S,* ,H,+,x,D,o,…)
- 颜色color(b,g,r,y,k,w,…)
- plot函数可以同时绘制多条曲线
- pandas包对plot的支持
plt.plot([1, 2, 3, 4], [2, 3, 1, 7], 'H-') #“H”代表六边形,“-”代表线
plt.show()
plt.plot([1, 2, 3, 4], [2, 3, 1, 7], '+:') #“:”代表线虚线
plt.show()
Markers
character | description |
---|---|
'.' |
point marker |
',' |
pixel marker |
'o' |
circle marker |
'v' |
triangle_down marker |
'^' |
triangle_up marker |
'<' |
triangle_left marker |
'>' |
triangle_right marker |
'1' |
tri_down marker |
'2' |
tri_up marker |
'3' |
tri_left marker |
'4' |
tri_right marker |
's' |
square marker |
'p' |
pentagon marker |
'*' |
star marker |
'h' |
hexagon1 marker |
'H' |
hexagon2 marker |
'+' |
plus marker |
'x' |
x marker |
'D' |
diamond marker |
'd' |
thin_diamond marker |
``’ | '`` |
'_' |
hline marker |
Line Styles
character | description |
---|---|
'-' |
solid line style |
'--' |
dashed line style |
'-.' |
dash-dot line style |
':' |
dotted line style |
Colors
The supported color abbreviations are the single letter codes
character | color |
---|---|
'b' |
blue |
'g' |
green |
'r' |
red |
'c' |
cyan |
'm' |
magenta |
'y' |
yellow |
'k' |
black |
'w' |
white |
Example format strings::
'b' # blue markers with default shape
'or' # red circles
'-g' # green solid line
'--' # dashed line with default color
'^k:' # black triangle_up markers connected by a dotted line
1.2 plot-函数周边
# 同时画两条线
plt.plot([1, 2, 3, 4], [2, 3, 1, 7], color='red')
plt.plot([1, 2, 3, 4], [3, 5, 6, 9], color='blue', marker='o')
plt.show()
- 设置图像标题:plt.title()
- 设置x轴名称:plt.xlabel()
- 设置y轴名称:plt.ylabel()
- 设置x轴范围:plt.xlim()
- 设置y轴范围:plt.ylim()
- 设置x轴刻度:plt.xticks()
- 设置y轴刻度:plt.yticks()
- 设置曲线图例:plt.legend()
plt.plot([1, 2, 3, 4], [2, 3, 1, 7], color='red')
plt.plot([1, 2, 3, 4], [3, 5, 6, 9], color='blue', marker='o')
plt.title('Matplotlib Test Plot')
plt.xlabel('xlabel')
plt.ylabel('ylabel')
plt.show()
# 绘图显示中文乱码解决办法
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
plt.plot([1, 2, 3, 4], [2, 3, 1, 7], color='red')
plt.plot([1, 2, 3, 4], [3, 5, 6