Matplotlib精品学习笔记001-图形绘制常见的组分有哪些?

简介

从头学习,逐步精美

学习蓝本

学习资料是Quick start

内容

所有绘图的起始步骤

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

通过一个简单的例子认识Matplotlib绘图的过程,见代码注释

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

fig, ax = plt.subplots() # 创建包含一个轴区(ax)的fig(图形)
ax.plot([1,2,3,4], [2, 3,1,4]) # 在ax中绘制散点图(plot)

plt.show() # 显示图形

散点图

matplotlib图形的组成了解

在这里插入图片描述

Figure(图形)

即图形整体。图形包含着所有的轴区(即axes),其余的都是特殊的艺术组件,包括标题(titles)、figure legends(图例)、colorbars(色带)甚至嵌套的子图形(subfigures)等等。

创建图形的方法有3种,各有所好

fig = plt.figure()  # 创建没有ax的空白图形
fig, ax = plt.subplots()  # 创建含有一个ax的空白图形
fig, axs = plt.subplots(2, 2)  # 创建含有2x2排列的ax的空白图形
axes(轴区)

轴区(axes)是图形(figure)里占据一定面积的区域,通常有2条轴线(axis)(或者3D里有3条)。轴线(axis)的刻度(ticks)和刻度标签(ticks labels)为在轴区中利用数据绘制提供标尺。

每个轴区(axes)都有单独的标题(set_title()),X轴标签(set_xlabel())和Y轴标签(set_ylabel())。

轴区是应用大部分绘图方法的对象。

axis(轴线)

轴线可以设置标尺(scale)、标尺范围(limits),还可以生成刻度(ticks,轴线上的标记)和刻度标签(ticklabels,刻度的文字标签)。刻度的位置是由定位器(Locator)决定的,刻度标签由格式器(Formatter)进行格式化。定位器和格式器的精确联合能精准控制刻度的位置和标签。

artist(艺术器)

图形上任何可视的元素都是艺术器(artist),包括前文介绍的三种。还包括文本(Text)、线形2D(line2D)、收集器(collections)、修补器(pathc)等等。绘制图形就是将各个艺术器展现在画布(canvas)上。大多数艺术器都应用在一个轴区上,不能共享或转移。

绘图的输入数据类型

绘图时最好输入numpy.array或numpy.ma.masked_array类型数据,或者能转换成numpy.asarray的数据。类似的数据类型,比如pandas数据类型和numpy.matrix都不接受。通常在绘图前要把不接受的数据类型转换未numpy.array。以numpy.matrix为例:

b = np.matrix([[1, 2], [3, 4]])
b_asarray = np.asarray(b)

大部分的绘图方法会尝试解析例如numpy.recarray和pandas.DataFrame的字典数据。Matplotlib可以通过data关键字参数传参,并通过x和y位置的键值(key)查找data传参的对值(value)。

np.random.seed(19680801)  # 随机数
data = {'a': np.arange(50),
        'c': np.random.randint(0, 50, 50),
        'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.scatter('a', 'b', c='c', s='d', data=data)
ax.set_xlabel('entry a')
ax.set_ylabel('entry b')
编码类型
显式和隐式接口
  • 直接创建图形(fig)和轴区(axes),然后对其调用函数(面向对象风格
  • 通过pyplot间接创建和控制图形(fig)和轴区(axes),使用pyplot功能绘图

更多详细信息请阅读Matplotlib显式与隐式接口有何不同?

面向对象风格的例子:

x = np.linspace(0, 2, 100)  # 创建简单的数据

# 注意,即使在面向对象风格中,也是采用.pyplot.figure创建图形
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
ax.plot(x, x, label='linear')  # 向轴区里绘制图形
ax.plot(x, x**2, label='quadratic')  # 向轴区里绘制更多图形
ax.plot(x, x**3, label='cubic')  # 继续绘制
ax.set_xlabel('x label')  # 向轴区添加X轴标签
ax.set_ylabel('y label')  # 向轴区添加Y轴标签
ax.set_title("Simple Plot")  # 向轴区添加标题
ax.legend()  # 添加图例

pyplot风格:

x = np.linspace(0, 2, 100)  # Sample data.

plt.figure(figsize=(5, 2.7), layout='constrained')
plt.plot(x, x, label='linear')  # Plot some data on the (implicit) axes.
plt.plot(x, x**2, label='quadratic')  # etc.
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
plt.legend()

还有第三种使用方法,当Matplotlib被嵌入GUI时,就要完全抛弃pyplot甚至figure的建立。详解matplotlib嵌入tkinter

辅助函数

如果你要用不同的数据在同一块区域绘图,或者希望能更简便地调用Matplotlib方法,可以采用下面的方法:

def my_plotter(ax, data1, data2, param_dict):
    """
   通过辅助函数绘图
    """
    out = ax.plot(data1, data2, **param_dict)
    return out

data1, data2, data3, data4 = np.random.randn(4, 100)  #创建4个随机数组
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(5, 2.7))
my_plotter(ax1, data1, data2, {'marker': 'x'}) # 利用辅助函数绘图
my_plotter(ax2, data3, data4, {'marker': 'o'}) # 利用辅助函数绘图

为艺术器选择样式

为艺术器选择样式,既可以在调用绘图函数时,也可以通过艺术器的设值函数(setter)。请看例子:

fig, ax = plt.subplots(figsize=(5, 2.7))
x = np.arange(len(data1))
ax.plot(x, np.cumsum(data1), color='blue', linewidth=3, linestyle='--') # 调用绘图(plot)函数时直接配置color、linewidth和linestyle样式
l, = ax.plot(x, np.cumsum(data2), color='orange', linewidth=2)
l.set_linestyle(':') # 在绘图后,通过设值函数set_linestyle选择样式
颜色(color)

绝大多数艺术器(artist)都有颜色属性。一些艺术器接受多个颜色,比如散点图(scatter)可以为标记点边缘和内部配置不同的颜色:

fig, ax = plt.subplots(figsize=(5, 2.7))
ax.scatter(data1, data2, s=50, facecolor='C0', edgecolor='k')
线宽,线样式,标记点大小(Linewidths,linestyles和markersizes)

线宽的基本单位是印刷点(1 pt = 1/72 inch) , 所有可以绘线的艺术器都能配置线宽,进而也可以配置线样式。详情可以参考matplotlib线样式

标记点大小取决于绘图方法。plot函数通常用印刷点表示标记的直径或宽度。scatter函数则是通过倍数来控制标记大小。

fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(data1, 'o', label='data1')
ax.plot(data2, 'd', label='data2')
ax.plot(data3, 'v', label='data3')
ax.plot(data4, 's', label='data4')
ax.legend()

绘制标签

轴区(Axes)标签和文本

set_xlabel, set_ylabel, set_title分别用于配置X轴标签,Y轴标签和标题。通过text()可以直接向图中增添文本。

mu, sigma = 115, 15
x = mu + sigma * np.random.randn(10000)
fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
# the histogram of the data
n, bins, patches = ax.hist(x, 50, density=True, facecolor='C0', alpha=0.75)

ax.set_xlabel('Length [cm]')
ax.set_ylabel('Probability')
ax.set_title('Aardvark lengths\n (not really)')
ax.text(75, .025, r'$\mu=115,\ \sigma=15$')
ax.axis([55, 175, 0, 0.03])
ax.grid(True)
添加注释(Annotations)

注释一般由注释文本和指向某处的箭头组成。

fig, ax = plt.subplots(figsize=(5, 2.7))

t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2 * np.pi * t)
line, = ax.plot(t, s, lw=2)

ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
            arrowprops=dict(facecolor='black', shrink=0.05))

ax.set_ylim(-2, 2)
添加图例(Legends)
fig, ax = plt.subplots(figsize=(5, 2.7))
ax.plot(np.arange(len(data1)), data1, label='data1')
ax.plot(np.arange(len(data2)), data2, label='data2')
ax.plot(np.arange(len(data3)), data3, 'd', label='data3')
ax.legend()

轴的标尺和刻度(axis scales and ticks)

每个轴区都有两个轴对象(axis objects),分别表示x轴和y轴。它们控制着轴的标尺,刻度的位置和刻度的格式。

标尺(scales)

matplotlib除了线形标尺外,还有非线性标尺,比如对数标尺(log-scale)。

fig, axs = plt.subplots(1, 2, figsize=(5, 2.7), layout='constrained')
xdata = np.arange(len(data1))  # make an ordinal for this
data = 10**data1
axs[0].plot(xdata, data)

axs[1].set_yscale('log')
axs[1].plot(xdata, data)
刻度的定位器和格式器

每个轴对象都有的刻度定位器和格式器决定着刻度标记在轴上的位置。set_xticks()就是决定X轴刻度的简单接口。

fig, axs = plt.subplots(2, 1, layout='constrained')
axs[0].plot(xdata, data1)
axs[0].set_title('Automatic ticks')

axs[1].plot(xdata, data1)
axs[1].set_xticks(np.arange(0, 100, 30), ['zero', '30', 'sixty', '90'])
axs[1].set_yticks([-1.5, 0, 1.5])  # note that we don't need to specify labels
axs[1].set_title('Manual ticks')
添加日期和字符串

Matplotlib可以利用日期数组或字符串数组进行绘图,期间会生成合适的定位器和格式器。例如日期:

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
dates = np.arange(np.datetime64('2021-11-15'), np.datetime64('2021-12-25'),
                  np.timedelta64(1, 'h'))
data = np.cumsum(np.random.randn(len(dates)))
ax.plot(dates, data)
cdf = mpl.dates.ConciseDateFormatter(ax.xaxis.get_major_locator())
ax.xaxis.set_major_formatter(cdf)

还有字符串:

fig, ax = plt.subplots(figsize=(5, 2.7), layout='constrained')
categories = ['turnips', 'rutabaga', 'cucumber', 'pumpkins']

ax.bar(categories, np.random.rand(len(categories)))

操作多个Figures和Axes

可以通过多次调用fig = plt.figure() 或 fig2, ax = plt.subplots()来创建多个Figures。之后可以向每个Figures中增加Artist。

创建多个Axes的方法很多,最常用的就是plt.subplots()。可以通过subplot_mosaic按行列来创建复杂的Axe对象。

fig, axd = plt.subplot_mosaic([['upleft', 'right'],
                               ['lowleft', 'right']], layout='constrained')
axd['upleft'].set_title('upleft')
axd['lowleft'].set_title('lowleft')
axd['right'].set_title('right')

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ALittleHigh

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

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

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

打赏作者

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

抵扣说明:

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

余额充值