Matplotlib学习笔记

本文详细介绍了Python的可视化库Matplotlib,包括其介绍、安装、基本绘图方法如图片与子图、折线图、散点图、条形图、直方图、饼图、雷达图和箱型图的绘制,以及Axes和Axis容器的使用,多图布局和配置项的调整,还有3D立体图形的绘制。无论你是初学者还是进阶用户,都能找到所需的知识。
摘要由CSDN通过智能技术生成

1 matplotlib介绍与安装

1.1 matplotlib介绍

matplotlib是一个Python的基础绘图库,它可与Numpy一起使用来代替MATLAB,主要用于在Python中创建静态,动画和交互式可视化图形。

1.2 matplotlib的安装

安装命令:pip install matplotlib
注意:优先使用换源安装,安装完成之后可在pythcharm的终端(terminal)输入命令:pip list 可以查看目前安装的所有包名。

2 matplotlib绘图

2.1 图片与子图

matplotlib所绘制的图位于figure对象中,我们可以通过plt.figure生成一个新的figure对象

from matplotlib import pyplot as plt
fig = plt.figure()

注意:在IPthon中,执行该代码会出现一个空白的绘图窗口,但在jupter中则没有任何显示。

通过plt.subplot()方法创建一个或多个子图,如下面带有四个子图的matplotlib图片:

image.png

plt.subplot() 方法参数:plt.subplot(*arg,**kwargs)

'''
Parameters
    ----------
    *args : int, (int, int, *index*), or `.SubplotSpec`, default: (1, 1, 1)
        The position of the subplot described by one of

        - Three integers (*nrows*, *ncols*, *index*). The subplot will take the
          *index* position on a grid with *nrows* rows and *ncols* columns.
          *index* starts at 1 in the upper left corner and increases to the
          right. *index* can also be a two-tuple specifying the (*first*,
          *last*) indices (1-based, and including *last*) of the subplot, e.g.,
          ``fig.add_subplot(3, 1, (1, 2))`` makes a subplot that spans the
          upper 2/3 of the figure.
        - A 3-digit integer. The digits are interpreted as if given separately
          as three single-digit integers, i.e. ``fig.add_subplot(235)`` is the
          same as ``fig.add_subplot(2, 3, 5)``. Note that this can only be used
          if there are no more than 9 subplots.
        - A `.SubplotSpec`.

    projection : {None, 'aitoff', 'hammer', 'lambert', 'mollweide', \
'polar', 'rectilinear', str}, optional
        The projection type of the subplot (`~.axes.Axes`). *str* is the name
        of a custom projection, see `~matplotlib.projections`. The default
        None results in a 'rectilinear' projection.

    polar : bool, default: False
        If True, equivalent to projection='polar'.

    sharex, sharey : `~.axes.Axes`, optional
        Share the x or y `~matplotlib.axis` with sharex and/or sharey. The
        axis will have the same limits, ticks, and scale as the axis of the
        shared axes.

    label : str
        A label for the returned axes.

    Returns
    -------
    `.axes.SubplotBase`, or another subclass of `~.axes.Axes`

        The axes of the subplot. The returned axes base class depends on
        the projection used. It is `~.axes.Axes` if rectilinear projection
        is used and `.projections.polar.PolarAxes` if polar projection
        is used. The returned axes is then a subplot subclass of the
        base class.

    Other Parameters
    ----------------
    **kwargs
        This method also takes the keyword arguments for the returned axes
        base class; except for the *figure* argument. The keyword arguments
        for the rectilinear base class `~.axes.Axes` can be found in
        the following table but there might also be other keyword
        arguments if another projection is used.

        %(Axes)s
'''

该方法具体用法看代码源文件。

实例:

# 从matplotlib中导入pyplot类
from matplotlib import pyplot as plt

# 创建图片对象
fig = plt.figure()

'''
添加子图到figure对象中
-- nrows 行
-- ncols 列
-- index 取子图得索引,从1开始
'''
# 2 x 2 四个子图,如果index的值大于子图的索引范围会报错。
ax1 = plt.subplot(2,2,1)
ax2 = plt.subplot(2,2,2)
ax3 = plt.subplot(2,2,3)
ax4 = plt.subplot(2,2,4)
# plt.subplot(2,2,5)会报错

# 绘制图形。比如散点图(x,y)构成点
ax1.scatter(range(10),range(10))
ax2.scatter(range(10),range(10))
ax3.scatter(range(10),range(10))
ax4.scatter(range(10),range(10))

# 注意,如果通过plt直接绘制,默认在最后一个子图中绘制图形
plt.scatter(range(10),range(10))

# 展示图形,在pycharm中呈现图形必须使用plt.show()方法

另外,matplotlib可以用另一个便捷方法plt.subplots()创建figure对象并设置了子图,因此有两个返回值:figure和axes。

plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,subplot_kw=None, gridspec_kw=None, **fig_kw)

参数介绍

  • nrows,ncols:整型,默认为1,控制子图网格的行数/列数。

  • sharex,sharey:布尔型或者{‘none’, ‘all’, ‘row’, ‘col’},默认为False,用来控制所有子图使用相同的x轴刻度/y轴刻度。其中:

    • True or ‘all’: x- or y-axis will be shared among all subplots.

    • False or ‘none’: each subplot x- or y-axis will be independent.

    • ‘row’: each subplot row will share an x- or y-axis.

    • ‘col’: each subplot column will share an x- or y-axis.

  • squeeze:布尔型,默认为True。

    (1) 如果为True,则对子图进行压缩。

    • 如果只绘制一个子图(即nrows=ncols=1),则生成单个子图作为标量返回。

    • 如果绘制 N x 1 或者 1 x M 个子图,则返回Axes对象的一维numpy数组对象。

    • 如果绘制 N x M (N>1,M>1)个子图,则返回一个2维数组。

    (2)如果为False,则不对子图进行压缩,返回始终包含Axes实例的2D数组(即使是1x1)

实例1

import matplotlib.pyplot as plt
    
# 创建2*2的子图
fig,axs = plt.subplots(2,2)
    
# 通过下标(从0开始)访问子图
# 例如:axs[0][0]
    
# 绘制图形
axs[0,0].scatter(range(10),range(10))
axs[0,1].scatter(range(10),range(10))
axs[1,0].scatter(range(10),range(10))
axs[1,1].scatter(range(10),range(10))
    
# 展示图形
plt.show()

实例2

import numpy as np
from matplotlib import pyplot as plt
   
# First create some toy data:
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
   
# Create just a figure and only one subplot
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title("Simple plot")

如果不需要使用子图时,可以通过matplotlib.pyplot()方法绘制图形。

2.2 matplotlit绘制图形

matplotlib能够绘制的图形有:折线图、散点图、条形图、直方图、饼图等等。

具体可参考:
https://matplotlib.org/gallery/index.html

2.2.1 折线图

折线图介绍 :以折线的上升下降来表示统计数量的增减变化的统计图。

特点:能够显示数据的变化趋势,反映事物的变化情况。

image.png

折线图绘制:折线图可以通过matplotlib.pyplot.plot()方法来绘制
实例

import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [2,3,1,2]

plt.plot(x,y)
plt.show()

注意:x和y必须拥有相同的长度,即 len(x) = len(y)

以上实例,x数组对应图形x轴的值,y数组对应图形y轴的值,并且通过plt.plot()绘制之后, 通过plt.show()展示图片,释放内存。

plt.plot()函数除了传入制图数据,还可以设置线的颜色等:

  • color 设置线的颜色
  • linestyle 设置线的样式
  • marker 标记样式

例如:

import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [2,3,1,2]

plt.plot(x,y,color='g',linestyle='--')
plt.show()

plt.plot()参数使用具体可参考:https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html#matplotlib.axes.Axes.plot

图形的组成除了x,y轴,还有很多其他组件,图片地址:
https://cdn.nlark.com/yuque/0/2020/png/704747/1585837534064-b69d73b6-ee2b-42e1-ac5e-b81ed8bd8266.png

方法 描述
plt.figure(figsize=None,dpi=None) 生成新的图片,figsize:图片大小,dpi:透明度
plt.savefig(filename) 保存图片
plt.xticks(ticks=None) 设置x轴刻度的值
plt.yticks(ticks=None) 设置y轴刻度的值
plt.xlabel(xlabel) 设置x轴标签
plt.ylabel(ylabel) 设置y轴标签
plt.title() 设置图形标题
plt.grid() 根据x轴和y轴的数值展示轴网格

中文显示问题
当我们需要设置轴标签、标题等,通常会用到中文,但matplotlib默认不显示中文。
解决方法

  • 方法一:全局的方式。注意该方式只支持ttf,不支持ttc。
import matplotlib
font = {
   
    'family':'SimHei',
    'weight':'bold',
    'size':12
}
matplotlib.rc('font',**font)
  • 方法二:通过rcParams参数配置(局部的方式)
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']	# 步骤一:替换sans-serif字体
plt.rcParams['axes.unicode_minus'] = False		# 步骤二:解决坐标轴负数的负号显示问题
  • 方法三:读取系统自带的字体
from matplotlib import pyplot as plt
from matplotlib.font_manager import FontProperties

font = FontProperties(fname=r'c:\windows\fonts\simsun.ttc',size=14)

x = [1,2,3,4]
y = [3,2,
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值