【Note】MV-数据处理系列 之 画图Matplotlib

2018-12-13  本文已影响0人  火禾子_

如果某天你发现自己要学习 Matplotlib, 很可能是因为:

所以就找到了 Matplotlib. 它能帮你画出美丽的:
线图; 散点图; 等高线图; 条形图; 柱状图; 3D 图形, 甚至是图形动画等等.

一、基本使用

1、figure 图像 - 简单的线条
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2
plt.figure(num = 3, figsize=(8, 5), )
plt.plot(x, y2)
plt.plot(x, y1, color = 'red', linewidth = 1.0, linestyle = '--')
plt.show()
2、设置坐标轴

调整名字和间隔
设置坐标轴的范围,单位长度,替代文字等。

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color = 'red', linewidth = 1.0, linestyle = '--')
# 定义坐标轴范围
plt.xlim((-1, 2))
plt.ylim(-2, 3)
# 定义坐标轴的范围及个数
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
# 定义坐标轴的刻度及名称
plt.yticks([-2, -1.8, -1, 1.22, 3], [r'$really\ bad$', r'$bad$', r'$normal$', '$good$', '$really good$'])
# 定义坐标轴名称
plt.xlabel('I am X')
plt.ylabel('I am Y')

plt.show()

调整不同名字和位置
移动 axis 坐标轴的位置

import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x+1
y2 = x**2
plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color = 'red', linewidth = 1.0, linestyle = '--')
plt.xlim((-1, 2))
plt.ylim(-2, 3)
new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3], [r'$really\ bad$', r'$bad$', r'$normal$', '$good$', '$really good$'])
# 获取当前坐标轴信息
ax = plt.gca()
# 使用 .spines 设置边框
ax.spines['right'].set_color('green')
ax.spines['top'].set_color('red')
# 使用 .xaxis.set_ticks_position 设置x坐标刻度数字或名称的位置
# x 位置有: top,bottom,both,default,none
ax.xaxis.set_ticks_position('bottom')
# 使用 .set_position 设置边框位置
# 位置属性有 outward,axes,data
ax.spines['bottom'].set_position(('data', 0))
# 使用 .yaxis.set_ticks_position 设置y坐标刻度数字或名称的位置
# y 位置有: left,right,both,default,none
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

plt.show()
3、Legend 图例

legend 图例就是为了帮我们展示出每个数据对应的图像名称. 更好的让读者认识到你的数据结构.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
plt.ylim((-2, 3))
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
# legend 将要显示的信息来自于上面代码中的 label
# plt.plot() 返回的是一个列表. 因此 l1 l2 后有逗号
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
plt.legend(loc='upper right')
# 如果想单独修改之前的 label 信息, 给不同类型的线条设置图例信息. 可在 plt.legend 输入更多参数.
# loc 参数有:
# 'best' : 0,
# 'upper right'  : 1,
# 'upper left'   : 2,
# 'lower left'   : 3,
# 'lower right'  : 4,
# 'right'        : 5,
# 'center left'  : 6,
# 'center right' : 7,
# 'lower center' : 8,
# 'upper center' : 9,
# 'center'       : 10,
plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='best')

plt.show()
4、Annoction 标注

当图线中某些特殊地方需要标注时,我们可以使用annotation. matplotlib中的 annotation. 有两种方法, 一种是用 plt 里面的 annotate,一种是直接用 plt 里面的text来写标注.

import matplotlib.pyplot as plt
import numpy as np
# 画出基本图
x = np.linspace(-3, 3, 50)
y = 2*x + 1
plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)
# 移动坐标轴
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 标注出点的基本信息
x0 = 1
y0 = 2 * x0 + 1
   # 画虚线,第一个列表是 x 坐标,第二个列表是 y 坐标
plt.plot([x0, x0], [0, y0], 'k--', linewidth = 2.5)
   # set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')
# 添加注释 annotate
# 其中参数xycoords='data' 是说基于数据的值来选位置,
# xytext=(+30, -30) 和 textcoords='offset points' 对于标注位置的描述 和 xy 偏差值,
# arrowprops是对图中箭头类型的一些设置.
plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
# 添加注释 text
# 其中-3.7, 3,是选取text的位置, 空格需要用到转字符\ ,fontdict设置文本字体.
plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

plt.show()
5、tick 能见度
import matplotlib.pyplot as plt
import numpy as np
# 基本图
x = np.linspace(-3, 3, 50)
y = 0.1 * x
plt.figure()
# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
plt.plot(x, y, linewidth = 10, zorder = 1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
# 调整坐标
   # 其中label.set_fontsize(12)重新调节字体大小,
   # bbox设置目的内容的透明度相关参,facecolor调节 box 前景色,edgecolor 设置边框, 本处设置边框为无,alpha设置透明度.
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='white', edgecolor='none', alpha=0.7, zorder=2))

plt.show()

二、画图种类

1、Scatter 散点图
先上效果图,太美啦,不信你不想学!!!
import matplotlib.pyplot as plt
import numpy as np
# 生成服从正态分布的随机数
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y, X)
plt.scatter(X, Y, s=75, c=T, alpha=.5) # alpha 设置透明度
plt.xlim(-1.5, 1.5)
plt.xticks(())  # ignore xticks
plt.xlim(-1.5, 1.5)
plt.yticks(())  # ignore yticks

plt.show()
2、Bar 柱状图
同样先上效果图
import matplotlib.pyplot as plt
import numpy as np
# 生成基本图形
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)
plt.bar(X, -Y2)
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
# 加颜色和数据
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor = 'white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor = 'white')
# 横向对齐方式:ha 纵向对齐:va
for x, y in zip(X, Y1):
    plt.text(x, y+0.05, '%.2f'%y, ha='center', va='bottom')
for x, y in zip(X, Y2):
    plt.text(x, -y-0.05, '%.2f'%y, ha='center', va='top')

plt.show()
3、Contours 等高线图
老规矩,先放效果图:
import matplotlib.pyplot as plt
import numpy as np
def f(x, y):
    # the height function, 用来生成高度值
    return (1 - x/2 + x**5 + y**3) * np.exp(- x**2 - y**2)
n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y) # 在二维平面将 x 和 y 对应起来,编织成栅格
# 使用函数 plt.contourf 进行颜色填充
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)
# 使用函数 plt.contour 进行等高线的绘制
# 其中 8 代表等高线的密集程度,主要分为10个部分,如果是 0 ,则图像被一分为二
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
# 添加高度数字,inline 控制是否将 Label 画在线里面
plt.clabel(C, inline = True, fontsize = 10)
plt.xticks(())
plt.yticks(())

plt.show()
4、Image 图片
照例,效果图在此:
# 这里打印的是纯粹的数字,不是自然图像
# 用 3*3 的 2D-array 来表示点的颜色,每个点就是一个 pixel
import matplotlib.pyplot as plt
import numpy as np

a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
# origin 选择原点的位置
plt.imshow(a, interpolation = 'nearest', cmap='bone', origin='lower')
# 添加 colorbar,shrink 参数使得长度变为原来的 92%
plt.colorbar(shrink = .92)
plt.xticks(())
plt.yticks(())
plt.show()

其中,plt.imshow 中的 interpolation 参数的选择可在这个链接 可以看到matplotlib官网上对于内插法的不同方法的描述。
下图是一个示例:

5、3D 数据
效果图哦:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D  # 进行 3D 坐标轴显示
# 定义一个图像窗口,在窗口上添加 3D 坐标轴
fig = plt.figure()
ax = Axes3D(fig)
# 设置 x*y 栅格,以及用函数设置 z 值
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# plot 3D 图像
# rstride cstride 分别代表 row 和 column 的跨度, 颜色填充 colormap rainbow
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
# 将上面的三维图像投影到 XY 平面,做一个等高线图
# zdir='z' 保证了沿 z 轴做投影
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
ax.set_zlim(-2, 2)

plt.show()

三、多图合并显示

1、Subplot 多合一显示

均匀图中图

import matplotlib.pyplot as plt
plt.figure()
plt.subplot(2, 2, 1)
plt.plot([0, 1], [0, 1])
plt.subplot(2, 2, 2)
plt.plot([0, 1], [0, 2])
plt.subplot(223)
plt.plot([0, 1], [0, 3])
plt.subplot(224)
plt.plot([0, 1], [0, 4])
plt.show()

不均匀图中图


这里需要解释下为什么要在第4个位置放第2个小图。因为程序写了plt.subplot(2,3,4)后,就以为我们两行都分成了三列,所以这时候程序会把第2行的第一列当作是第4个小图。
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(2, 1, 1)
plt.plot([0, 1], [0, 1])
plt.subplot(2, 3, 4)
plt.plot([0, 1], [0, 2])
plt.subplot(235)
plt.plot([0, 1], [0, 3])
plt.subplot(236)
plt.plot([0, 1], [0, 4])
plt.show()
2、Subplot 分格显示

matplotlib 的 subplot 还可以是分格的,这里介绍三种方法.
subplot2grid

import matplotlib.pyplot as plt
plt.figure()
# 使用plt.subplot2grid来创建第1个小图, (3,3)表示将整个图像窗口分成3行3列, (0,0)表示从第0行第0列开始作图,
# colspan=3表示列的跨度为3, rowspan=1表示行的跨度为1. colspan和rowspan缺省, 默认跨度为1.
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan = 3)
ax1.plot([1, 2], [1, 2])
ax1.set_title('ax1_title')
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax5 = plt.subplot2grid((3, 3), (2, 1))
ax4.scatter([1, 2], [2, 2])
ax4.set_xlabel('ax4_x')
ax4.set_ylabel('ax4_y')
plt.show()

gridspec

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.figure()
gs = gridspec.GridSpec(3, 3)
ax6 = plt.subplot(gs[0, :])
ax7 = plt.subplot(gs[1, :2])
ax8 = plt.subplot(gs[1:, 2])
ax9 = plt.subplot(gs[-1, 0])
ax10 = plt.subplot(gs[-1, -2])
plt.show()

subplots

import matplotlib.pyplot as plt
# 使用plt.subplots建立一个2行2列的图像窗口,sharex=True表示共享x轴坐标, sharey=True表示共享y轴坐标.
# ((ax11, ax12), (ax13, ax14))表示第1行从左至右依次放ax11和ax12, 第2行从左至右依次放ax13和ax14.
f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
ax11.scatter([1, 2], [1, 2])
plt.tight_layout() # 表示紧凑显示图像
plt.show()
3、图中图
康忙,效果图:
import matplotlib.pyplot as plt
fig = plt.figure()
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]
# 首先绘制 大图
# 以下 4 个值,是指占整个 figure 坐标系的百分比
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
ax1.plot(x, y, 'r')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.set_title('title')
# 绘制左上角的小图,注意坐标系位置和大小的改变
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b') # 注意对 y 进行了逆序处理
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.set_title('title inside 1')
# 绘制右下角的小图,采用更简单的方法,直接往 plt 里添加新的坐标系
plt.axes([0.6, 0.2, 0.25, 0.25])
plt.plot(y[::-1], x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title('title inside 2')
plt.show()
4、次坐标轴
效果图依旧:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1
# 获取 figure 的默认坐标系 ax1
fig, ax1 = plt.subplots()
# 对 ax1 调用 twinx(),生成如同镜面效果后的 ax2
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-') # green, solid line
ax1.set_xlabel('x data')
ax1.set_ylabel('y1 data', color='g')
ax2.plot(x, y2, 'b-')
ax2.set_ylabel('y2 data', color='b')
plt.show()

四、动画

Animation 动画

使用matplotlib做动画也是可以的,我们使用其中一种方式,function animation来说说, 具体可参考matplotlib animation api

from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
# 构造自定义动画函数 animate,用来更新每一帧桑各 x 对应的 y 坐标值,参数表示第 i 帧
def animate(i):
    line.set_ydata(np.sin(x + i/10.0))
    return line,
# 构造开始帧函数 init
def init():
    line.set_ydata(np.sin(x))
    return line,
# 调用 FuncAnimation 函数生成动画。参数说明:
# fig 进行动画绘制的figure
# func 自定义动画函数,即传入刚定义的函数animate
# frames 动画长度,一次循环包含的帧数
# init_func 自定义开始帧,即传入刚定义的函数init
# interval 更新频率,以ms计
# blit 选择更新所有点,还是仅更新产生变化的点。应选择True,但部分mac用户请选择False,否则无法显示动画
ani = animation.FuncAnimation(fig=fig,
                              func=animate,
                              frames=100,
                              init_func=init,
                              interval=20,
                              blit=True)
plt.show()
上一篇下一篇

猜你喜欢

热点阅读