Python常用包之matplotlib的使用

0. 安装并导入

安装:
打开终端输入pip3 install matplotlib

导入:

import matlpotlib as plt

1. 绘图

绘图:

plt.plot(x, y, ,'r', linewidth=2.0)

x:横坐标值
y:纵坐标值
‘r’:红色
linewidth:线的粗细

无论绘制什么图最后都得加上一句:

plt.show()

图像才能显示。

2. 绘制图例plt.legend()

例子:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 11)

fig = plt.figure(1)
l1, = plt.plot(x, x*x, 'r')  # 这里关键哦
l2, = plt.plot(x, x*x*x, 'b')  # 注意

# 其中,loc表示位置的;
plt.legend([l1, l2], ['first', 'second'], loc='upper left', fontsize=8)  

plt.show()

在这里插入图片描述

loc: best,upper right,upper left,lower left,lower right,right,center left,center right,lower center,upper center,center

相关参数:

legend(loc  # Location code string, or tuple (see below).
            #  图例所有figure位置。  labels  # 标签名称。
    prop    # the font property.
            #  字体参数
    fontsize  # the font size (used only if prop is not specified).
              #  字号大小。
    markerscale  # the relative size of legend markers vs.
                 # original  图例标记与原始标记的相对大小
    markerfirst  # If True (default), marker is to left of the label.
                 #  如果为True,则图例标记位于图例标签的左侧
    numpoints  # the number of points in the legend for line.
               #  为线条图图例条目创建的标记点数
    scatterpoints  # the number of points in the legend for scatter plot.
                  #  为散点图图例条目创建的标记点数
    scatteryoffsets    # a list of yoffsets for scatter symbols in legend.
                    #  为散点图图例条目创建的标记的垂直偏移量
    frameon    # If True, draw the legend on a patch (frame).
               #  控制是否应在图例周围绘制框架
    fancybox    # If True, draw the frame with a round fancybox.
                #  控制是否应在构成图例背景的FancyBboxPatch周围启用圆边
    shadow    # If True, draw a shadow behind legend.
                #  控制是否在图例后面画一个阴影
    framealpha  # Transparency of the frame.
                #  控制图例框架的 Alpha 透明度
    edgecolor    # Frame edgecolor.
    facecolor    # Frame facecolor.
    ncol    # number of columns.
            #  设置图例分为n列展示
    borderpad    # the fractional whitespace inside the legend border.
                # 图例边框的内边距
    labelspacing    # the vertical space between the legend entries.
                  #  图例条目之间的垂直间距
    handlelength    # the length of the legend handles.
                  #   图例句柄的长度
    handleheight    # the height of the legend handles.
                  #   图例句柄的高度
    handletextpad    # the pad between the legend handle and text.
                    #   图例句柄和文本之间的间距
    borderaxespad    # the pad between the axes and legend border.
                    #  轴与图例边框之间的距离
    columnspacing    # the spacing between columns.
                    #  列间距
    title    # the legend title.
             #  图例标题
    bbox_to_anchor    # the bbox that the legend will be anchored.
                    #  指定图例在轴的位置
    bbox_transform)    # the transform for the bbox.
                    # transAxes if None.

3. 定义图像的各种属性plt.figure()

figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)

"""
      num : 图像编号或名称,数字为编号,字符串为名称
  figsize : 指定figure的宽和高,单位为英寸
      dpi : 指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80
facecolor : 背景的颜色
edgecolor : 边框颜色
  frameon : 是否显示边框
"""

例子:

import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4, 3), facecolor='blue')
plt.plot(y)
plt.show()

4. 绘制子图plt.subplot()

plt.subplot(nrows, ncols, index, **kwargs)

(1)第一个参数:*args

可以使用三个整数,或者三个独立的整数来描述子图的位置信息。如果三个整数是行数、列数和索引值,子图将分布在行列的索引位置上。索引从1开始,从右上角增加到右下角。

位置是由三个整型数值构成,第一个代表行数,第二个代表列数,第三个代表索引位置。举个列子:plt.subplot(2, 3, 5) 和 plt.subplot(235) 是一样一样的。需要注意的是所有的数字不能超过10。

(2)第二个参数:projection : {None, ‘aitoff’, ‘hammer’, ‘lambert’, ‘mollweide’, ‘polar’, ‘rectilinear’, str}, optional

可选参数:可以选择子图的类型,比如选择polar,就是一个极点图。默认是none就是一个线形图。

(3)第三个参数:polar : boolean, optional

如果选择true,就是一个极点图,上一个参数也能实现该功能。

例子:

import matplotlib.pyplot as plt
fig = plt.figure()
plt.subplot(2, 1, 1) # 将界面分成上下两份,左右一份,在第一份上绘图
plt.subplot(2, 1, 2) # 将界面分成上下两份,左右一份,在第二份上绘图
plt.show()

结果:
在这里插入图片描述

例子:

import matplotlib.pyplot as plt
fig = plt.figure()
curve1 = [1,2,3,4,5]
curve2 = [1,4,9,16,25]
plt.subplot(2, 1, 1) # 将界面分成上下两份,左右一份,在第一份上绘图
plt.plot(curve1)
plt.subplot(2, 1, 2) # 将界面分成上下两份,左右一份,在第二份上绘图
plt.plot(curve2)
plt.show()

结果:
在这里插入图片描述

5. 在图片中添加文字

(1)自由添加plt.text()

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)

其中x和y是要添加的文字在图片中的位置,s是要添加的内容。

例子:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5])
plt.text(0,5, "text")
plt.show()

在这里插入图片描述

(2)添加标题plt.title()

plt.title('title_name', size=23)

会在图片顶部正中显示标题

(3)添加x轴和y轴的名字plt.xlabel(), plt.ylabel()

font1 = {'size':23}  # 设置字体大小
plt.xlabel('x_name', font1)
plt.ylabel('y_name', font1)

6. 绘制散点图plt.scatter()

matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, *, data=None, **kwargs)

参数:

(1)x, y

x和y是大小为(n,)的数组,也就是我们即将绘制散点图的x坐标的数组和y坐标的数组。

(2)s
绘制点的大小

(3)c

表示的是颜色,也是一个可选项。默认是蓝色’b’,表示的是标记的颜色,或者可以是一个表示颜色的字符,或者是一个长度为n的表示颜色的序列等等,感觉还没用到过现在不解释了。但是c不可以是一个单独的RGB数字,也不可以是一个RGBA的序列。可以是他们的2维数组(只有一行)

(4)marker

表示的是标记的样式,默认的是’o’。

(5)求一个x

>>> x = np.linspace(1,10,10)
>>> x
array([1,2,3,4,5,6,7,8,9,10])

或者:

>>> x = list(range(10))
>>> x
[0,1,2,3,4,5,6,7,8,9]

7.在图中绘制竖直和水平分割线

(1)绘制竖直分割线

vlines(x, ymin, ymax)

第一个参数是竖直分割线的横坐标,第二、第三个参数分别是竖直分割线的最高点和最低点纵坐标。

(2)绘制水平分割线

hlines(y, xmin, xmax) 

第一个参数是水平分割线的纵坐标,第二、第三个参数分别是水平分割线的最小和最大的横坐标。

8.逐点打印

for i in range(len(list_1)):
	axes.plot(list_1[i], list_2[i], marker='x' if MSE_lable[i] == 1 else 'o', linestyle='', color='r' if MSE_lable[i] == 1 else 'g', label='Anomaly' if MSE_lable[i] == 1 else "Normal")

9.定义图像的坐标范围

plt.xlim([0.0, 1.0]) # x轴的范围在0.0-1.0之间
plt.ylim([0.0, 1.05]) # y轴的范围在0.0-1.05之间

10.设置图片的分辨率

plt.figure(dpi=200)  #分辨率设置为200

在plt.figure()中也可以设置其他的参数,如图像大小等,如果不设置分辨率系统会有一个默认的分辨率。

11. 如何在图片中显示中文

  • 字体设置:首先,您需要选择一个支持中文的字体,并将其配置为Matplotlib的默认字体。您可以使用matplotlib.rcParams来配置全局字体设置。例如,可以使用以下代码将字体设置为SimHei(中文简体))
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'SimHei'
  • 如果缺少字体文件即使设置了也会出乱码:
    在Windows上,可以从其他计算机上复制所需的字体文件(通常位于C:\Windows\Fonts目录下),并将其粘贴到Python环境的字体目录中;在Linux上,您可以通过在终端中运行fc-list :lang=zh命令来查找系统中可用的中文字体,并选择一个字体文件。然后,将该字体文件复制到Matplotlib的字体目录中。
    可以使用以下代码查找Matplotlib的字体目录:
import matplotlib
print(matplotlib.get_cachedir())
  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

comli_cn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值