pythonLibs(5) - Matplotlib

matplotlib 常用函数 和 对应的参数 列表

  1. color, fontsize常用参数,线、文字(label, title, text)相关函数都会涉及。
  2. label - 图例、 title - 标题、 text - 文字说明、annotate - 点坐标
  3. 使用plt是在默认的子图上操作,相关方法可以直接使用在子图上(subplot)
# 1. plt.figure() 初始化参数
plt.figure(num=None,       # a unique identifier for the figure (int or str)
		   figsize=None,   # 画布大小(default: [6.4, 4.8] in inches.)
		   dpi=None,       # The resolution of the figure in dots-per-inch.
		   facecolor=None,  # The background color
		   edgecolor=None, # The border color
		   frameon=True,   # If False, suppress drawing the figure frame.
		   FigureClass=<class 'matplotlib.figure.Figure'>, 
		   clear=False,    # If True and the figure already exists, then it is cleared.
		   **kwargs
)

# 2. plt.savefig() 保存画布
plt.savefig(fname,               # fname:**A string containing a path to a filename**, or a Python file-like object, or possibly some backend-dependent object such as PdfPages.(保存图片位置与路径的字符串)
            dpi=None,            # None | scalar > 0 | ‘figure’
            facecolor=’w’, 
            edgecolor=’w’,
            orientation=’portrait’, 
            papertype=None, 
            format=None,         # png, pdf, ps, eps and svg
            transparent=False, 
            bbox_inches=None, 
            pad_inches=0.1,
            frameon=None)
          
# 3. plt.plot() 绘制曲线
plt.plot(x, y,              # list, np.array, x, y 轴数据,
         color="deeppink",   # string, 折线的颜色,
         alpha=None,         # float, [0, 1]透明度
         label='Jay income', # string, 图例, 配合plt.legend(fontsize=20)使用
         linewidth=2,        # int, 线宽度
         linestyle='-',      # string, 线形
         marker='o',         # string, 表示折线上数据点处的类型
)

# 4. plt.title() 图标题
plt.title(fontsize    # 设置字体大小,默认12,可选参数 ['xx-small', 'x-small', 'small', 'medium', 'large','x-large', 'xx-large']
          fontweight  # 设置字体粗细,可选参数 ['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']
          fontstyle   # 设置字体类型,可选参数[ 'normal' | 'italic' | 'oblique' ],italic斜体,oblique倾斜
          verticalalignment   # 设置水平对齐方式 ,可选参数 : 'center' , 'top' , 'bottom' ,'baseline' 
          horizontalalignment # 设置垂直对齐方式,可选参数:left,right,center
          rotation            # (旋转角度)可选参数为:vertical,horizontal 也可以为数字
          alpha               # 透明度,参数值0至1之间
          backgroundcolor # 标题背景颜色
          bbox            # 给标题增加外框
          boxstyle        # 方框外形
          facecolor       # (简写fc)背景颜色
          edgecolor       # (简写ec)边框线条颜色
          edgewidth       # 边框线条大小
)
plt.title('xxxx',fontsize='large')         # 隐式初始化(画布)图像标题设置
figure.suptitle("xxxx")                    # 显示初始化,设置画布标题
ax.set_title('xxxx',fontsize=12,color='r') # 显式初始化(子图/坐标系)标题

# 5. plt.text() 文字说明
plt.text(s,                      # str,待显示内容
		 x, y,                   # scalars, 标识放置text的位置,图横纵坐标位置
		 transform=ax.transAxes,# 执定标注相对于子图的位置
		 fontdict=None,          # dict, 用于定义s的格式,
		 withdash=False,         # boolean, optional, default: False。如果True则创建一个 TextWithDash实例。
		 color,                  # 文字颜色
		 fontsize,               # 文字大小
		 **kwargs
)
ax.text(0.01, 0.95, "test string", transform=ax.transAxes, fontdict={'size': '16', 'color': 'b'}) # 设置文本,目标位置 左上角,距离 Y 轴 0.01 倍距离,距离 X 轴 0.95倍距离

# 6. plt.xlim() 坐标轴范围
plt.xlim(-5, 5)
plt.ylim(0, 80)
axes.set_xlim(-5, 5)
axes.set_ylim(0, 80)

# 7. set_xticks() 坐标轴刻度
plt.xticks([-np.pi, -np.pi/2, np.pi/2, np.pi],
           [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$\pi$"])
ax.set_xticks([0,20,40,60])
ax.set_xticklabels(['one','two','three','four'], rotation=30) 

# 8. grid() 子图网格
plt.grid(b,              # True可视化网格,None网格不可见
         which='major',  # 网格线显示的尺度, 可选 {'major', 'minor', 'both'}, 主次刻度详细见参考文档7
         axis='both',    # 显示网格线的轴,可选 {'both', 'x', 'y'}
         **kwargs        #  Line2D线条对象属性
)

# 9 axes.set_xlabel() 坐标轴名称
axes.set_xlabel("t(s)")
axes.set_ylabel("v(m/s)")

# 10. set_aspect() 横纵轴坐标比例,缩放
axes.set_aspect(0.5)
plt.axis("equal")  # 等比例缩放 可以达到和as_spect()一样的效果,详见参看文档8
Plt.axis("scaled") # 等比例缩放,坐标值标的很小,曲线出描绘框架

# 11. plt.legend()图例 
axes.legend() # 极简设置

train_x = np.linspace(-1, 1, 100)
train_y_1 = 2*train_x + np.random.rand(*train_x.shape)*0.3
train_y_2 = train_x**2+np.random.randn(*train_x.shape)*0.3
p1 = plt.scatter(train_x, train_y_1, c='red', marker='v' )
p2= plt.scatter(train_x, train_y_2, c='blue', marker='o' )
legend = plt.legend([p1, p2], ["CH", "US"], facecolor='blue')# 复杂设置,省略[p1, p2] 直接写图例

1. 安装导入

Matplotlib 是 Python 的绘图库,它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。其子库pyplot包含大量与MatLab相似的函数调用接口。

pip install matplotlib
pip install --upgrade matplotlib # 升级

import numpy as np
from matplotlib import cm
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

matplotlib绘图三个核心概念– figure(画布)、axes(坐标系)、axis(坐标轴) , 如图1-1
fig-1
绘图步骤: 导入相关库 -> 初始化画布 -> 准备绘图数据 -> 将数据添加到坐标系中 -> 显示图像/保存图像

注:可以绘制list,也可以绘制Numpy数组

2. figure() 画布初始化、保存

  1. 隐式创建 - 第一次调用plt.xxx时[诸如:plt.plot(x,y)],系统自动创建figure对象,并在figure上创建一个axes坐标系,基于此进行绘图操作(隐式初始化只能绘制一张图)。
  2. 显示创建 - 手动创建figure对象,在画布中添加子图axes。
  3. 画布显示、保存 - plt.show() 以阻塞方式显示图片,只有关掉显示窗口,代码才会继续运行。plt.savefig(“test.png”)可以将图片保存下来查看,来保障程序运行的流畅性,
def test_init_figure():
    """
    Function: 画布初始化设置
        plt.show()                # 以图片阻塞的方式显示图片,只有关掉显示窗口,代码才会继续运行
        plt.savefig("test.png")   # 可以选择将图片存盘,保障程序运行的流畅性。"test.png"将图像以png的形式存在当前文件夹下
        plt.close()               # 存完图关闭画布,防止内存占满
    """
    # 1. 系统自动创建figure对象,并在figure上创建一个axes坐标系,基于此进行绘图操作(隐式初始化只能绘制一张图)
    x = [1, 3, 5,7]
    y = [4, 9, 6, 8]
    plt.plot(x,y)
    path = "test_init0.png"
    plt.savefig(path)

    # 2. 手动创建一个figure对象,在画布中添加坐标系axes 
    figure = plt.figure(figsize=[6.4, 4.8])
    axes1 = figure.add_subplot(1,1,1)
    x = [1, 2, 5, 7]
    y = [4, 4, 4, 4]
    axes1.plot(x, y)
    path = "test_init1.png"
    plt.savefig(path)
    plt.close()

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

3. plot() 折线绘制

def test_plot(show=False):
    """
    Function: 测试曲线绘制的基本功能
    """
    figure = plt.figure(figsize=([12.8, 9.6]))
    ax_dict = {}
    row, col = 2, 2
    grid_spec = gridspec.GridSpec(row, col)
    # 子图 合并
    # ax_dict["sin"] = figure.add_subplot(row, col, 1) # 2 * 2 的 第1个图
    # ax_dict["cos"] = figure.add_subplot(row, col, 3) # 2 * 2 的 第3个图
    ax_dict["sin"] = plt.subplot(grid_spec[0, 0]) # 2 * 2 的 第1个图
    ax_dict["cos"] = plt.subplot(grid_spec[1, 0]) # 2 * 2 的 第3个图
    ax_dict["tmp"] = plt.subplot(grid_spec[:, 1]) # 2 * 2 的 第二列

    # 坐标轴范围 lim()
    min_x, max_x = -5.0, 5.0
    min_y, max_y = -2.0, 2.0
    ax_dict["sin"].set_xlim(min_x, max_x)
    ax_dict["sin"].set_ylim(min_y, max_y)
    ax_dict["cos"].set_xlim(min_x, max_x)
    ax_dict["cos"].set_ylim(-5.0, 5.0)

    # 横纵坐标比例
    ax_dict["cos"].set_aspect(1.0)

    # 坐标轴刻度 ticks()
    x_ticks = [-np.pi, -np.pi/2, 0, np.pi/2, np.pi]
    x_ticks_label = ["-pi", "pi/2", "0", "pi/2", "pi"]
    ax_dict["sin"].set_xticks(x_ticks)
    ax_dict["sin"].set_xticklabels(x_ticks_label)
    ax_dict["sin"].set_yticks(np.arange(min_y, max_y, 1))

    # 坐标轴网格 grid()
    ax_dict["sin"].grid(which="major", axis="both")
    ax_dict["cos"].grid(which="major", axis="both")

    # 坐标轴图例
    ax_dict["sin"].set_xlabel("x")
    ax_dict["sin"].set_ylabel("y")

    # 画布 标题
    ax_dict["sin"].set_title("test sin", fontsize=12)
    ax_dict["cos"].set_title("test cos", fontsize=12)

    # construct data
    x = np.linspace(min_x, max_x, 20)
    y1 = np.sin(x)
    y2 = np.cos(x)
    ax_dict["sin"].plot(x, y1, label="sin", marker="o", color="g",)
    ax_dict["cos"].plot(x, y2, label="cos", marker='*', color="b", linestyle="-")

    ax_dict["sin"].legend()
    ax_dict["cos"].legend()

    # 文字说明
    ax_dict["sin"].text(0.05, 0.95, "Hello", transform=ax_dict["sin"].transAxes,
                        verticalalignment="top", horizontalalignment="left", fontsize=8)

    figure.suptitle("TestMatplotLib", fontsize=16)
    if show:
        plt.show()
    else:
        path = "test.png"
        plt.savefig(path)        # 保存图像
    plt.close()              # 关闭画布

在这里插入图片描述

4. 绘制各类图像

曲线图:plt.plot()
散点图:plt.scatter()
柱状图:plt.bar()
等高线图:plt.contourf()
在等高线图中增加label:plt.clabel()
矩阵热图:plt.imshow()
在随机矩阵图中增加colorbar:plt.colorbar()
直方图 plt.hist( data, bin)

4.1 等高线

import matplotlib.pyplot as plt
n=256
x=np.linspace(-3,3,n)
y=np.linspace(-3,3,n)
X,Y=np.meshgrid(x,y) #把X,Y转换成网格数组,X.shape=nn,Y.shape=nn
plt.contourf(X,Y,height(X,Y),8,alpha=0.75,cmap=plt.cm.hot)
#8:8+2=10,将高分为10部分,
#alpha:透明度
#cmap:color map
#use plt.contour to add contour lines
C=plt.contour(X,Y,height(X,Y),8,colors=“black”,linewidth=.5)
#adding label
plt.clabel(C,inline=True,fontsize=10)
#clabel:cycle的label,inline=True表示label在line内,fontsize表示label的字体大小
plt.show()

参考博文:https://cloud.tencent.com/developer/article/1544887

4.2 箭头arrow

 arrow_x1 = x_list[0]
 arrow_x2 = x_list[10]
 arrow_y1 = y_list[0]
 arrow_y2 = y_list[10]
 self.axis1.arrow(arrow_x1, arrow_y1, arrow_x2-arrow_x1, arrow_y2-arrow_y1, 
		width=0.1, length_includes_head=True, head_width=1,head_length=3, fc='b',ec='b')

参考文档:matplotlib 画箭头的两种方式

4.3 柱状、饼状、曲线 子图

plt.subplot()方法产生的坐标系都是按照网格方式划分的,不能随意划分位置和尺寸大小

# 20210406
# 1.柱状图
plt.subplot(2,1,1)
n = 12
X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white")
plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white")

# 利用plt.text 指定文字出现的坐标和内容
for x, y in zip(X,Y1):
    plt.text(x+0.4, y+0.05, "%.2f" % y, ha="center", va="bottom")
# 限制坐标轴的范围
plt.ylim(-1.25, +1.25)

# 2.饼状图
plt.subplot(2,2,3)
n = 20
Z = np.random.uniform(0, 1, n)
plt.pie(Z)

# 3.第三部分
plt.subplot(2, 2, 4)
# 等差数列
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
Y_C, Y_S = np.cos(X), np.sin(X)

plt.plot(X, Y_C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, Y_S, color="red", linewidth=2.5, linestyle="-")

# plt.xlim-限定坐标轴的范围,plt.xticks-改变坐标轴上刻度的文字
plt.xlim(X.min() * 1.1, X.max() * 1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
           [r"$-\pi$", r"$-\pi/2$", r"$0$", r"$+\pi/2$", r"$\pi$"])
plt.ylim(Y_C.min()*1.1, Y_C.max()*1.1)
plt.yticks([-1, 0, 1],
           [r"$-1$", r"$0$", r"$+1$"])
#plt.show()
plt.savefig("test.png")

在这里插入图片描述

5. 色卡

def test_color(show=False):
    """
    Function: 利用柱状图显示色块
    cm_names = ['Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds',
                      'YlOrBr', 'YlOrRd', 'OrRd', 'PuRd', 'RdPu', 'BuPu',
                      'GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn']
    cm.YlGn(0.5) = (0.46720492313889894, 0.77480970200370336, 0.47278739108758816, 1.0)
    """

    cla_colors = ["red", "green", "blue", "rosybrown", "yellowgreen", "turquoise", 
                 "teal", "dodgerblue", "violet", "pink"]
    cm_keys = ["YlGn", "GnBu", "BuPu", "PuRd", "OrRd", "Greys"]
    cm_colors = [cm.YlGn(0.5), cm.GnBu(0.5), cm.BuPu(0.5), cm.PuRd(0.5), cm.OrRd(0.5), cm.Greys(0.5)]
    str_n, cm_n = len(cla_colors), len(cm_colors)
    
    figure = plt.figure(figsize=[12.8, 9.6])
    ax_dict = {}
    ax_dict["rgb"] = figure.add_subplot(2, 1, 1)
    ax_dict["cm"] = figure.add_subplot(2, 1, 2)
    ax_dict["rgb"].set_xlim(-0.5, str_n)
    ax_dict["rgb"].set_ylim(-0.5, 2)
    ax_dict["cm"].set_xlim(-0.5, cm_n)
    ax_dict["cm"].set_ylim(-0.5, 2)
    
    x = np.linspace(0, str_n - 1, str_n)
    values = [1] * str_n
    ax_dict["rgb"].bar(x, values, color=cla_colors)
    for idx in range(str_n):
        cla_str = cla_colors[idx]
        ax_dict["rgb"].text(idx, -0.1, cla_str, color=cla_str)

    x = np.linspace(0, cm_n - 1, cm_n)
    values = [1] * cm_n
    ax_dict["cm"].bar(x, values, color=cm_colors)
    for idx in range(cm_n):
        ax_dict["cm"].text(idx, -0.1, cm_keys[idx], color=cm_colors[idx])

    if show:
        plt.show()
    else:
        path = "test_color.png"
        plt.savefig(path)        # 保存图像
    plt.close()

在这里插入图片描述

matplotlib.colorbar

plt.colorbar()
fig.colorbar(norm=norm, cmap=cmp ax=ax) # norm色卡数字范围,cmap 调制颜色
https://blog.csdn.net/sinat_32570141/article/details/105345725

6. Other

6.1 RuntimeError: Invalid DISPLAY variable
在远端服务器上运行时报错,本地运行并没有问题
原因:matplotlib的默认backend是TkAgg,而FltAgg、GTK、GTKCairo、TkAgg、Wx和WxAgg这几个backend都要求有GUI图形界面,所以在ssh操作的时候会报错。
解决:在导入matplotlib的时候指定不需要GUI的backend(Agg、Cairo、PS、PDF和SVG)。

import matplotlib.pyplot as plt
plt.switch_backend(‘agg’)

6.2 画布占满警告
RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (matplotlib.pyplot.figure) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam figure.max_open_warning).
max_open_warning, RuntimeWarning)
需要plt.close()

6.3 Seaborn
Seaborn是一种基于matplotlib的图形可视化python libraty。它提供了一种高度交互式界面,便于用户能够做出各种有吸引力的统计图表。

参考资料
https://baijiahao.baidu.com/s?id=1659039367066798557&wfr=spider&for=pc
https://www.kesci.com/home/column/5b87a78131902f000f668549
https://blog.csdn.net/gdkyxy2013/article/details/79585922

6.4 Bokeh
针对浏览器中图形演示的交互式绘图工具。目标是使用d3.js样式(不懂)提供的优雅,简洁新颖的图形风格,同时提供大型数据集的高性能交互功能。
他提供的交互式电影检索工具蛮吸引我的吼,并打不开这个网址,😭。
http://demo.bokehplots.com/apps/movies


Reference

  1. 图1-1 matplotlib绘图的核心原理讲解

  2. matplotlib可视化篇hist()–直方图

  3. matplotlib—多图布局(subplot()函数、add_subplot()函数、axes()和add_axes()函数、subplots()函数)

  4. matplotlib.pyplot.text()结构及用法||参数详解

  5. matplotlib命令与格式:标题(title),标注(annotate),文字说明(text)

  6. Python中的set_xticks和set_xticklabels用法(附代码解释)

  7. python画图坐标轴主刻度和次刻度

  8. matplotlib之pyplot模块之坐标轴配置(axis():设置坐标轴外观、设置坐标轴范围)

  9. python绘图使用matplotlib色卡

Python学习笔记(4)——Matplotlib中的annotate(注解)的用法
matplotlib xticks用法
matplotlib.pyplot 标记出曲线上最大点和最小点的位置
matplotlib 中子图subplot 绘图时标题重叠解决办法(备忘)

  • 0
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值