【Python数据可视化】matplotlib库的基本配置

1.1 matplotlib的介绍

(1)安装

anaconda环境:自带matplotlib,无需另外安装
     
其他Python环境:
             1. win+R 输入cmd进入控制台。
             
             2. 查看是否有pip(下载Python解释器会自带):pip --version 
             
             3. 更新一下 pip:python.exe -m pip install --upgrade pip
        
             4. 将 pip 从国外源改成国内源(在Pycharm终端使用) :
                 pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/
                 pip config set global.install.trusted-host mirrors.aliyun.com
                 
             5.下载matplotlib库:python -m pip install matplotlib 
             
             6.下载pandas库:pip install pandas -i https://pypi.tuna.tsinghua.edu.cn/simple/
             
             7.下载完后看看里面有没有 matplotlib pandas:python -m pip list 

(2)课程介绍

matplotlib是Python中的数据可视化软件包之一,支持跨平台运行(不同的操作系统),它是Python常用的2D绘图库,同时它也提供了一部分3D绘图接口。

matplotlib通常与Numpy、Pandas一起使用,是数据分析中不可或缺的重要工具之一。

(3)导包

# 导入 数据分析 三大部分
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

1.2 matplotlib的绘图基本参数配置

(1)导包

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

(2)配置

# 运行时配置参数
# rcParams:runtime configuration Parameters

# 让图片可以显示中文
plt.rcParams['font.sans-serif'] = 'SimHei'  

# 让图片中可以显示负号
plt.rcParams['axes.unicode_minus'] = False



# 如果浏览器不显示图片,就需要加上这句话
%matplotlib inline

# 支持svg矢量图
%config Inlinebackend.figure_format = 'svg'

(3)查看自己电脑上的字体库

from matplotlib.font_manager import FontManager

fm = FontManager()
my_font = set(f.name for f in fm.ttflist)
print(my_font)

在这里插入图片描述

案例:画一个2D基本绘图(抛物线)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'  
plt.rcParams['axes.unicode_minus'] = False

# 定义抛物线
x = np.linspace(-5,5,50)   # 等差数列  -5 ~ 5之间等分成50份       提供50个点(数据)
y = x ** 2

# 画图:线性图(折线图)
plt.plot(x,y)

# 输出结果
plt.show() 

在这里插入图片描述

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'  
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-5,5,5)              # 提供5个点(数据)
y = x ** 2

plt.plot(x,y)

plt.show()

在这里插入图片描述

(4)样式和颜色

样式(ls:line style  ):
‘-’  ‘--’  ‘-.’  ‘:’  ‘.’   ‘,’ ‘ ’
 o   ^   v   <   >   s   +   x   D
 d   1   2   3   4   h   H   p   |  _
 
颜色(color):
 b(蓝色)  g(绿色)  r(红色)  c(青色)  m(品红)  y(黄色)  k(黑色)  w(白色)

案例:将抛物线画成红色,并用虚线代替直线

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'  
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(-5,5,50)              
y = x ** 2

plt.plot(x,y,color = 'r' , ls = '--')
# color='r',ls='--'   的另一种写法 ————>   ’r--’

plt.show()

在这里插入图片描述

1.3 matplotlib的画布配置

(1)配置画布

# figsize:画布大小(宽度,高度)
# dpi:分辨率  像素密度(越大则图撑开的越大)
# facecolor:背景颜色

plt.figure(figsize = '' , dpi = '' , facecolor = '')

案例:画一个正弦曲线

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

# 画布配置
plt.figure(figsize=(6,2) , dpi = 200 , facecolor='red')

# 定义正弦曲线
x = np.linspace(0 , 2*np.pi)   # 2*np.pi = π
y = np.sin(x)

# 画图
plt.plot(x,y)

# 输出结果
plt.show()

在这里插入图片描述

plt.figure(figsize=(6,2) , dpi = 200,facecolor = 'red')

在这里插入图片描述

(2)设置网格

plt.grid()

案例:画一个背景为网格的正弦曲线

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(6,2) , dpi = 100 , facecolor='red')

plt.grid()

x = np.linspace(0 , 2*np.pi) 
y = np.sin(x)

plt.plot(x,y)

plt.show()

在这里插入图片描述

案例:在一个画布上绘制多个图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize = (5,3))

x = np.linspace(0,8)

plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x) , 'r')
plt.plot(x,-np.sin(x), 'g')

plt.show()

在这里插入图片描述

案例:立即显示图片

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize = (5,3))

x = np.linspace(0,8)

plt.plot(x,np.sin(x))
plt.show()

# 第二个plt.show( )会在新的画布中画

plt.plot(x,np.cos(x) , 'r')
plt.plot(x,-np.sin(x), 'g')
plt.show()

在这里插入图片描述
在这里插入图片描述

1.4 matplotlib的多图布局

(1)用subplot()函数 画子图

案例:在一块画布中画4个子图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(8,5))

x = np.linspace(-np.pi,np.pi,30)
y = np.sin(x)

# 子图1
ax1 = plt.subplot(221)   # 2行2列中的第1个图
ax1.plot(x,y)
ax1.set_title('子图1')

# 子图2
ax2 = plt.subplot(222)   # 2行2列中的第2个图
ax2.plot(x,y)
ax2.set_title('子图2')

# 子图3
ax3 = plt.subplot(2,2,3)   # 2行2列中的第3个图
ax3.plot(x,y)
ax3.set_title('子图3')

# 子图4
ax4 = plt.subplot(2,2,4)   # 2行2列中的第4个图
ax4.plot(x,y)
ax4.set_title('子图4')

plt.show()

在这里插入图片描述

# 自动调整布局(变紧凑  防重叠)
fig.tight_layout()

在这里插入图片描述

案例:在一块画布中画3个子图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(8,5))

x = np.linspace(-np.pi,np.pi,30)
y = np.sin(x)

# 子图1
ax1 = plt.subplot(2,2,1)
ax1.plot(x,y)

# 子图2
ax2 = plt.subplot(2,2,2)
ax2.plot(x,y)

# 子图3
ax3 = plt.subplot(2,1,2)    # 2行1列中的第2行
ax3.plot(x,np.sin(x*x))

fig.tight_layout()

plt.show()

在这里插入图片描述

(2)用subplots()函数 画子图

plt.subplots(3,3)   # 返回一个二维数组

在这里插入图片描述

案例:画3行3列的子图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

x = np.linspace(0 , 2*np.pi)

fig , ax = plt.subplots(3,3)
ax1 , ax2 , ax3 = ax
ax11 , ax12 ,ax13 = ax1
ax21 , ax22 ,ax23 = ax2
ax31 , ax32 ,ax33 = ax3

# fig 设置画布大小
fig.set_figwidth(8)
fig.set_figheight(5)

# 第一行
ax11.plot(x , np.sin(x))
ax12.plot(x , np.cos(x))
ax13.plot(x , np.tan(x))

# 第二行
ax21.plot(x , np.tanh(x))
ax22.plot(x , np.cosh(x))
ax23.plot(x , np.sinh(x))

# 第三行
ax31.plot(x , np.sin(x) + np.cos(x))
ax32.plot(x , np.sin(x*x) + np.cos(x*x))
ax33.plot(x , np.sin(x) * np.cos(x))


plt.tight_layout

plt.show()

在这里插入图片描述

1.5 matplotlib的图形嵌套

(1)用add_subplot()函数 画嵌套图

案例:画一个嵌套1个图的嵌套图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(8,5))

# 子图1
axes1 = fig.add_subplot(1,1,1)
axes1.plot([0,1],[1,3])

# 子图2  嵌套图
axes2 = fig.add_subplot(2,2,1 , facecolor = 'pink')
axes2.plot([1,3])

plt.show()

在这里插入图片描述

(2)用 axes()函数 或 add_axes()函数 画嵌套图

案例:画一个嵌套2个图的嵌套图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(8,5))

# 图1
x = np.linspace(0,2*np.pi,30)
y = np.sin(x)

plt.plot(x,y)

# 嵌套图1

# 参数顺序   [left,bottom,width,height]
axes1 = plt.axes([0.55,0.55,0.3,0.3])
axes1.plot(x,y,color = 'green')

# 嵌套图2
axes2 = fig.add_axes([0.18,0.18,0.3,0.3])
axes2.plot(x,y,color = 'red')

plt.show()

在这里插入图片描述

1.6 matplotlib的双轴显示(组合图)

exp()函数:指数函数

案例:画一个双轴显示的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(6,4))

x = np.linspace(0,10,100)

# 图1
axes1 = plt.gca()          # 得到 当前轴域
axes1.plot(x,np.exp(x), color = 'red')
axes1.set_xlabel('time')
axes1.set_ylabel('exp',color = 'red')
axes1.tick_params(axis='y',labelcolor = 'red')

# 图2
axes2 = axes1.twinx()      # 和图1 共享x轴
axes2.plot(x,np.sin(x),color = 'b')
axes2.set_ylabel('sin',color = 'b')
axes2.tick_params(axis='y',labelcolor = 'b')

plt.tight_layout

plt.show()

在这里插入图片描述

1.7 matplotlib的绘图属性

在这里插入图片描述
(1)图例

案例:画一个具有图例的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(6,4))

x = np.linspace(0,2*np.pi)

plt.plot(x,np.sin(x),label = 'sin')
plt.plot(x,np.cos(x),label = 'cos')

# 图例
plt.legend()

plt.show()

在这里插入图片描述

案例:画一个有具体图例位置的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(6,4))

x = np.linspace(0,2*np.pi)

plt.plot(x,np.sin(x),label = 'sin')
plt.plot(x,np.cos(x),label = 'cos')

plt.legend(['sin','cos'],fontsize = 18,loc = 'center',ncol = 2)    # legent()函数默认放置在左下角    ncol=‘’ 显示成几列

# 图例的具体位置 (x,y,width,height)
bbox_to_anchor = [0,0,1,1]

plt.show()

在这里插入图片描述

(2)线条属性

在这里插入图片描述

案例:画一个含有多个线条属性的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(6,4))

x = np.linspace(0,2*np.pi,20)
y1 = np.sin(x)
y2 = np.cos(x)

plt.plot(x,y1, color = 'r', marker = 'o' , ls = '--' , lw = 1 , label = 'sinx' , mfc = 'y')

plt.plot(x,y2, color = 'b', marker = '*' , ls = '-' , lw = 2 , label = 'cosx' , mfc = 'w' , markersize = 10)

plt.plot(x,y1-y2, color = 'y', marker = '^' , ls = '-' , lw = 3 , label = 'sinx-cosx' , mfc = 'b' ,
         markersize = 10,
         alpha = 0.5    # 透明度  范围在0~1之间
         )

plt.plot(x,y1+y2, color = 'orange', marker = '>' , ls = '-.' , lw = 4 , label = 'sinx+cosx' , mfc = 'y' ,
         markersize = 10 ,          # 标记大小
         markeredgecolor = 'green' ,# 标记(点)的边缘颜色
         markeredgewidth = 2        # 标记(点)的边缘宽度
         )

# 图例
plt.legend()

plt.show()

在这里插入图片描述

(3)坐标轴刻度

案例:画一个具有坐标轴刻度值的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(5,3))

x = np.linspace(0,10)
y = np.sin(x)

plt.plot(x,y)

plt.xticks(ticks = np.arange(0,11,1),    # 设置x轴的刻度值
           fontsize = 20 ,
           color = 'r' ,
           )

plt.yticks(ticks = [-1,0,1] ,            # 设置y轴的刻度值
           labels = ['min','0','max'] ,  # 显示刻度标签
           fontsize = 20,
           color = 'b',
           ha = 'right'
           )                 # 水平对齐方式

plt.show()

在这里插入图片描述

(4)坐标轴范围

案例:画一个具有坐标轴范围的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(5,3))

x = np.linspace(0,2*np.pi)
y = np.sin(x)

plt.plot(x,y,c = 'r')

plt.xlim(-2,8)     # 设置x轴的坐标轴范围
plt.ylim(-2,2)     # 设置y轴的坐标轴范围

# 另一种坐标轴范围方法  使用 axis()函数: [xmin,xmax,ymin,ymax]  
# plt.axis([-2,8,12,2])


plt.show()

在这里插入图片描述

(5)坐标轴配置

案例:画一个具有坐标轴配置的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(5,3))

x = np.linspace(0,2*np.pi)
y = np.sin(x)

plt.plot(x,y,c = 'r')

# option

# off:不显示坐标轴
# equal:让x轴和y轴 刻度距离相同
# scaled: 自动缩放坐标轴和图片匹配
# tight:紧凑型自动适配图片
# square:让画布呈现正方形  x轴和y轴宽高一致
plt.axis('scaled')

plt.show()

在这里插入图片描述

(6)标题和网格线

案例:画一个具有标题和网格线的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(5,3))

x = np.linspace(0,10)
y = np.sin(x)

plt.plot(x,y)

# 图的标题
plt.title('sin曲线' , fontsize = 20 , loc = 'center')

# 父标题
plt.suptitle('父标题' ,
             y = 1.1 ,   # 位置
             fontsize = 26
             )

# 网格线
# axis():让哪个轴显示网格线
plt.grid(ls = '--' , lw = 0.5 , c = 'gray' , axis = 'x')

plt.show()

在这里插入图片描述

(7)标签

案例:画一个坐标轴具有标签的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(5,3))

x = np.linspace(0,10)
y = np.sin(x)

plt.plot(x,y)

# 坐标轴的标签
# rotation:旋转角度
plt.xlabel('y=sin(x)' , fontsize = 20 , rotation = 45 )
plt.ylabel('y=sin(x)' , fontsize = 20 , rotation = 90 , horizontalalignment = 'right' )

plt.title('正弦曲线')

plt.show()

在这里插入图片描述

(8)画文本

案例:画一个具有文本的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(5,3))

x = np.linspace(1,10,10)
y = np.array([60,30,20,90,40,60,50,80,70,30])

plt.plot(x,y,ls = '--',marker = 'o')

# 画文字
# zip():将x,y两个数组中的数据一一对应    组合后形成一个元组
for a,b in zip(x,y):
    plt.text(
        x=a+0.3,   # x轴坐标
        y=b+1,   # y轴坐标
        s=b,   # 文本内容
        fontsize = 10,
        c = 'r',
        ha = 'center',   # 水平对齐方式
        va = 'center'   # 垂直对齐方式

    )
    
plt.show()

在这里插入图片描述

(9)注释标注

案例:画一个具有注释标注的图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

plt.figure(figsize=(5,3))

x = np.linspace(1,10,10)
y = np.array([60,30,20,90,40,60,50,80,70,30])

plt.plot(x,y,ls = '--',marker = 'o')

# 注释:标注
plt.annotate(
    text = '最高销量',          # 标注内容
    xy = (3.8,90),              # 标注的坐标点:箭头指向的位置
    xytext = (1,80),          # 标注内容的位置
    arrowprops = {
        'width':2,            # 箭头线的宽度
        'headwidth':8,        # 箭头头部的宽度
        'facecolor':'blue'    # 箭头的背景颜色
    }
)

plt.show()

在这里插入图片描述

(10)保存图片

案例:保存一个图(方法一)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(5,3))

x = np.linspace(0,2*np.pi)

plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x))

# 保存图片
plt.savefig('sincos.png')

plt.show()

在这里插入图片描述

案例:保存一个图(方法二)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False

fig = plt.figure(figsize=(5,3))

x = np.linspace(0,2*np.pi)

plt.plot(x,np.sin(x))
plt.plot(x,np.cos(x))

# 保存图片   注意不是运行图!!!!
fig.savefig(fname='sincos2.png',       # 文件拓展名支持:png  jpg
            dpi=100,                   # 保存图片的像素密度
            facecolor = 'pink',
            pad_inches = 1              # 内边距
            )

plt.show()

在这里插入图片描述
在这里插入图片描述

  • 9
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值