Matplotlib基础
一、本课目标
了解matplotlib的应用 掌握pyplot绘制线图 掌握pyplot绘制散点图 掌握pyplot绘制条形图 掌握pyplot绘制直方图 掌握pyplot绘制饼图
二、Matplotlib介绍
Matplotlib 是 Python 的绘图库,它能让使用者很轻松地将数据图形化,并且提供多样化的输出格式 Matplotlib 可以绘制线图、散点图、条形图、柱状图、饼图、3D 图形、甚至是图形动画等等
三、Matplotlib 应用
Matplotlib 通常与 NumPy 和 SciPy(Scientific Python)一起使用, 这种组合广泛用于替代 MatLab,是一个强大的科学计算环境,有助于我们通过 Python 学习数据科学或者机器学习。 SciPy 是一个开源的 Python 算法库和数学工具包。 SciPy 包含的模块有最优化、线性代数、积分、插值、特殊函数、快速傅里叶变换、信号处理和图像处理、常微分方程求解和其他科学与工程中常用的计算
四、Matplotlib 安装
安装 matplotlib 库:
pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple 安装完成后,我们就可以通过 import 来导入 matplotlib 库:
import matplotlib print(matplotlib. _version _)
五、Pyplot
Pyplot 是 Matplotlib 的子库,提供了绘图 API Pyplot 是常用的绘图模块,能很方便让用户绘制 2D 图表 Pyplot 包含一系列绘图函数的相关函数,每个函数会对当前的图像进行一些修改 使用 import 导入 pyplot 库,并设置一个别名 plt:
import matplotlib.pyplot as plt
六、Pyplot 常用函数
plot():用于绘制线图和散点图 scatter():用于绘制散点图 bar():用于绘制垂直条形图和水平条形图 hist():用于绘制直方图 pie():用于绘制饼图 show():用于绘制图像 subplots():用于创建子图
import matplotlib. pyplot as plt
import numpy as np
xpoints = np. array( [ 0 , 6 ] )
ypoints = np. array( [ 0 , 100 ] )
plt. plot( xpoints, ypoints)
plt. show( )
七、plot()方法
用于绘制点和线,语法格式如下:
画单条线:plot([x], y, [fmt], *, data=None, **kwargs) 画多条线:plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs) 参数说明:
x, y:点或线的节点,x 为 x 轴数据,y 为 y 轴数据,数据可以列表或数组。 fmt:可选,定义基本格式(如颜色、标记和线条样式)。 **kwargs:可选,用在二维平面图上,设置指定属性,如标签,线的宽度等。 常用颜色字符:‘b’ 蓝色,‘m’ 洋红色,‘g’ 绿色,‘y’ 黄色,‘r’ 红色,‘k’ 黑色,‘w’ 白色,‘c’ 青绿色。多条曲线不指定颜色时,会自动选择不同颜色。 常用线型参数:‘‐’ 实线,‘:’ 虚线。 常用标记字符:‘.’ 点标记,‘,’ 像素标记(极小点),‘o’ 实心圈标记
xpoints = np. array( [ 1 , 8 ] )
ypoints = np. array( [ 3 , 10 ] )
plt. plot( xpoints, ypoints, 'o' )
plt. show( )
xpoints = np. array( [ 1 , 2 , 6 , 8 ] )
ypoints = np. array( [ 3 , 8 , 1 , 10 ] )
plt. plot( xpoints, ypoints)
plt. show( )
ypoints = np. array( [ 3 , 10 ] )
plt. plot( ypoints)
plt. show( )
ypoints = np. array( [ 3 , 8 , 1 , 10 , 5 , 7 ] )
plt. plot( ypoints)
plt. show( )
x = np. arange( 0 , 4 * np. pi, 0.01 )
y = np. sin( x)
z = np. cos( x)
plt. plot( x, y, "r" , x, z, "y" )
plt. show( )
八、散点图
使用 pyplot 中的 scatter() 方法来绘制散点图
x = np. array( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] )
y = np. array( [ 1 , 4 , 9 , 16 , 7 , 11 , 23 , 18 ] )
plt. plot( x, y, "*" )
plt. show( )
x = [ ]
y = [ ]
for i in range ( 100 ) :
x. append( np. random. randint( 0 , 100 ) )
y. append( np. random. randint( 0 , 100 ) )
if i == 0 :
print ( x[ 0 ] , y[ 0 ] )
if i == 99 :
print ( x[ 99 ] , y[ 99 ] )
plt. scatter( x, y)
plt. plot( x, y)
plt. show( )
九、柱状图
x = np. array( [ "Season-1" , "Season-2" , "Season-3" , "Season-4" ] )
y = np. array( [ 12 , 22 , 6 , 18 ] )
plt. bar( x, y, width = 0.3 )
plt. show( )
df. plot( rot = 45 , kind = "barh" , title = "shai" )
df. plot( rot = 0 , kind = "bar" , title = "shai" )
plt. show( )
names = [ 'tom' , 'jack' , 'rose' ]
chinese = [ 90 , 80 , 70 ]
math = [ 85 , 90 , 75 ]
df = pd. DataFrame( { "chinese" : chinese, "math" : math} , names)
print ( df)
df. plot( kind = "bar" , rot = 0 , title = "mark" , xlabel= "names" , ylabel= "score" )
plt. show( )
十、饼图
使用 pyplot 中的 pie() 方法来绘制饼图
percent = [ 25 , 35 , 25 , 15 ]
plt. title( "Area" )
plt. pie( percent)
plt. legend( [ "A" , "B" , "C" , "D" ] )
plt. show( )
十一、直方图
使用 pyplot 中的 hist() 方法来绘制直方图
data = np. random. randn( 10000 )
plt. hist( data, bins = 30 , color = 'skyblue' )
zhfont = matplotlib. font_manager. FontProperties( fname= "SourceHanSansSC-Bold.otf" )
plt. rcParams[ "font.sans-serif" ] = [ "SimHei" ]
plt. title( '柱状图' )
plt. xlabel( 'value' )
plt. ylabel( 'Frequency' )
% config InlineBackend. figure_format= 'svg'
plt. show( )
十二、子图
x = np. arange( 0 , 10 , 0.5 )
y = np. sin( x)
z = np. cos( x)
ax1 = plt. subplot( 2 , 1 , 1 )
ax2 = plt. subplot( 2 , 1 , 2 )
ax1. plot( x, y, 'go-.' )
ax2. plot( x, z, 'go-.' )
ax1. grid( )
ax2. grid( )
ax1. set_title( 'sin(x)' )
ax2. set_title( 'cos(x)' )
plt. show( )
production = [ 1125 , 1725 , 2250 , 2875 , 2900 , 3750 , 4125 ]
temp = [ 6 , 8 , 10 , 13 , 14 , 16 , 21 ]
ax2 = plt. subplot( 2 , 2 , 3 )
ax2. scatter( temp, production)
plt. rcParams[ 'font.family' ] = 'SimHei'
plt. rcParams[ 'axes.unicode_minus' ] = False
labels = [ '果汁' , '矿泉水' , '绿茶' , '其他' , '碳酸饮料' ]
num = [ 6 , 10 , 11 , 8 , 15 ]
exploade = [ 0 , 0.2 , 0 , 0 , 0 ]
ax3 = plt. subplot( 2 , 2 , 4 )
ax3. pie( num, labels= labels, autopct= '%.2f%%' , shadow= True , startangle= 140 , explode= exploade)
% config InlineBackend. figure_format= 'svg'
plt. show( )
十三、中文显示-1
Matplotlib 中文显示不是特别友好,默认情况下,中文部分不能正常显示,可以通过以下两个方法:
设置 Matplotlib 的字体参数 下载使用支持中文的字体库 字体参数
plt.rcParams[‘font.family’] = 'SimHei
十四、中文显示-2
使用字体库
官网:https://source.typekit.com/source-han-serif/cn/ GitHub 地址:https://github.com/adobe-fonts/source-hansans/tree/release/OTF/SimplifiedChinese 将字体文件放在当前执行的代码目录中
#fname 为 你下载的字体库路径,注意 SourceHanSansSC-Bold.otf 字体的路径 zhfont = matplotlib.font_manager.FontProperties(fname=“SourceHanSansSCBold.otf”) … plt.title(“中文显示 - 测试”, fontproperties=zhfont) …
data = np. random. randn( 1000 )
plt. hist( data, bins = 30 , color = 'skyblue' )
zhfont = matplotlib. font_manager. FontProperties( fname= "SourceHanSansSC-Bold.otf" )
plt. title( "中文显示 - 测试" , fontproperties= zhfont)
plt. xlabel( 'Value' )
plt. ylabel( 'Frequency' )
plt. show( )
十五、总结
了解matplotlib的应用 掌握pyplot绘制线图 掌握pyplot绘制散点图 掌握pyplot绘制条形图 掌握pyplot绘制直方图 掌握pyplot绘制饼图