数据可视化系列之 matplotlib

matplotlib的数据可视化
matplotlib是python专门用于绘图的库,其官方指导网站为https://matplotlib.org/,里面涉及多种绘图的示例以及指导。这里只介绍一部分个人在平时使用中用到的一些方法。包括subplot,colormap,scatter等函数,处理实时绘图,多图间隔大小,多图叠加,标注等问题。

1.contour、pcolor、plot、scatter、imshow、matshow
以上各种方法都可以绘制三维数据。用法基本相同,具体参数看官方文档。

    for i in range(16):
        plt.subplot(4,4,i+1)
        plt.pcolor(conv2[0,:,:,i])

这里写图片描述

    fig, axes = plt.subplots(4, 4, figsize=(6, 6),
                         subplot_kw={'xticks': [], 'yticks': []})

    fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)
    for i,ax in zip(range(16), axes.flat):
        ax.imshow(conv2[0,:,:,i])
    plt.show()

这里写图片描述

2.subplot 控制绘图间距
方法1:subplot(nrows, ncols, plot_number)
方法2:matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)

import matplotlib.pyplot as plt
import numpy as np

methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16',
           'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric',
           'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']

# Fixing random state for reproducibility
np.random.seed(19680801)

grid = np.random.rand(4, 4)

fig, axes = plt.subplots(3, 6, figsize=(12, 6),
                         subplot_kw={'xticks': [], 'yticks': []})

fig.subplots_adjust(hspace=0.3, wspace=0.05)#控制间距
#fig.subplots_adjust(left=0.02, bottom=0.06, right=0.95, top=0.94, wspace=0.05)

for ax, interp_method in zip(axes.flat, methods):
    ax.imshow(grid, interpolation=interp_method, cmap='viridis')
    ax.set_title(interp_method)

plt.show()

这里写图片描述

3.多个figure绘图叠加

fig, ax = plt.subplots()

cmap = mpl.colors.ListedColormap(['blue','red'])

c = plt.pcolor(z,cmap = cmap,vmin = 0,vmax = 30)
plt.axis('tight')

fig.colorbar(c,ticks = [15])
plt.scatter(xid,yid,color = 'green')
for i in range(len(xid)):
    plt.text(xid[i]+10,yid[i]+10,str(cid[i]),ha = 'right')
plt.show()

这里写图片描述

4.数据实时绘图显示

import matplotlib.pyplot as plt
fig, (ax0, ax1) = plt.subplots(nrows = 2,figsize=(11, 9.6))
for i in range(10):
    ax0.scatter(i,j,color='b',marker='*')
    ax1.scatter(i,j*j,color='r',marker='*')
    plt.pause(0.001)
plt.show()

这里写图片描述

5.图表中显示中文
matplotlib的缺省配置文件中所使用的字体无法正确显示中文。为了让图表能正确显示中文,可以有几种解决方案。

  • 在程序中直接指定字体。
  • 在程序开头修改配置字典rcParams。
  • 修改配置文件。

      比较简便的方式是,中文字符串用unicode格式,例如:u”测试中文显示”,代码文件编码使用utf-8 加上 # coding = utf-8。
      但以上方法只是解决了标题部分显示中文的问题,并未解决图例中文显示的问题。可采用修改配置字典的方式设置图例显示中文,代码如下:

# 指定中文字体
mpl.rcParams['font.sans-serif'] = ['SimHei'] #指定默认字体

参考文献:
1.http://blog.csdn.net/sunhuaqiang1/article/details/70194015
更多的关于matplotlib的参考文档见官网指导文件。https://matplotlib.org/tutorials/index.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值