Matplotlib使用方法总结
一 模块导入
import matplotlib
.pyplot
as plt
二 基本流程
plt
.figure
(figsize
=(20,8),dpi
=100)
plt
.plot
([1,2,3,4,5],[10,23,45,56,90])
plt
.show
()
三 图像添加辅助功能
3.1 添加x,y轴刻度
plt
.plot
(x
,y
)
x_ticks_label
= ["10点{}分".format(i
) for i
in x
]
y_ticks
= range(50)
plt
.xticks
(x
[::5],x_ticks_label
[::5])
plt
.yticks
(y_ticks
[::5])
3.2 添加网格显示
plt
.grid
(True,linestyle
= "--",alpha
= 1)
3.3 添加描述信息
plt
.xlabel
("时间", fontsize
= 15)
plt
.ylabel
("温度", fontsize
= 15)
plt
.title
("10点到11点上海温度图",fontsize
= 20)
3.4 图像保存
注意:图像保存要在plt.show()之前,因为plt.show()会释放资源,否则保存空图片
plt
.savefig
("./temperature.png")
plt
.show
()
四 多次plot
(一幅图有多条线)
linestyle
- 实线- - 虚线-. 点划线: 点虚线’ ’ 留空、空格
plt
.plot
(x
,y_1
,color
="b",linestyle
="-.")
plt
.plot
(x
,y_2
,color
="r",linestyle
="--")
显示图例
字符数字
‘best’0‘upper right’1‘right’5‘center’10‘center left’6
plt
.plot
(x
,y_1
,color
="b",linestyle
="-.",label
="london")
plt
.plot
(x
,y_2
,color
="r",linestyle
="--",label
="franch")
plt
.legend
(loc
=0)
五 多个坐标系显示
x
= range(60)
y_1
= [random
.uniform
(20,27) for i
in x
]
y_2
= [random
.uniform
(5,15) for i
in x
]
fig
,axes
= plt
.subplots
(nrows
=1,ncols
=2,figsize
=(20,8),dpi
=100)
axes
[0].plot
(x
,y_1
,color
="b",linestyle
="-.",label
="london")
axes
[1].plot
(x
,y_2
,color
="r",linestyle
="--",label
="franch")
x_ticks_label
= ["10点{}分".format(i
) for i
in x
]
y_ticks
= range(50)
axes
[0].set_xticks
(x
[::5])
axes
[0].set_yticks
(y_ticks
[::5])
axes
[0].set_xticklabels
(x_ticks_label
[::5])
axes
[1].set_xticks
(x
[::5])
axes
[1].set_yticks
(y_ticks
[::5])
axes
[1].set_xticklabels
(x_ticks_label
[::5])
axes
[0].grid
(True,linestyle
= "--",alpha
= 1)
axes
[1].grid
(True,linestyle
= "--",alpha
= 1)
axes
[0].set_xlabel
("时间", fontsize
= 15)
axes
[0].set_ylabel
("温度", fontsize
= 15)
axes
[0].set_title
("10点到11点伦敦温度图",fontsize
= 20)
axes
[1].set_xlabel
("时间", fontsize
= 15)
axes
[1].set_ylabel
("温度", fontsize
= 15)
axes
[1].set_title
("10点到11点法国温度图",fontsize
= 20)
axes
[0].legend
(loc
=0)
axes
[1].legend
(loc
=0)
plt
.show
()
六 常见图形的绘制
6.1 散点图
plt
.figure
(figsize
=(20,8),dpi
=100)
plt
.scatter
(x
,y
)
plt
.show
()
6.2 柱形图
width : 柱状图的宽度 align : 每个柱状图的位置对齐方式,如‘center’
plt
.bar
(x
,y
,align
='center',width
=0.5,color
=["r","b","y","g","r"])
6.3 直方图
bins : 组距
plt
.hist
(x
, bins
=None)
6.4 饼图
labels:每部分名称 autopct:占比显示指定%1.2f%% colors:每部分颜色
plt
.pie
(x
, labels
=,autopct
=,colors
=)
注意事项: jupyter notebook中遇到中文显示问题时,在代码中加上下面一段话
设置中文显示:
from pylab
import mpl
mpl
.rcParams
["font.sans-serif"] = ["SimHei"]
mpl
.rcParams
["axes.unicode_minus"] = False