Matplolib Tips

Matplolib是最经常使用的Python数据绘图工具库,支持不一样样式数据的图像绘制。本文介绍一些使用Matplotlib库的注意事项,主要包括:html

  • subplots
  • 布局调整
  • specgram(光谱图)
  • pcolormesh
  • 样式加强

其余:python

  • 颜色集
  • 直方图Hist

subplots

subplots()是绘图的开始,建立不一样子图的排列结构。git

以下:github

import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
复制代码

最终的图像展现使用plt.show()方法。工具

返回:布局

  • fig:绘图的底版,用于显示整个背景轮廓,等同于plt.gcf();
  • axes:子图的集合,经过下标选中单个子图,如axes[0][0]

参数:spa

  • nrowsncols:子图排列的行和列;

非规则的排列,使用subplot2grid(),经过结构shape位置loc排列子图,如,排列5个子图,上三下二结构:code

ax1 = plt.subplot2grid(shape=(2, 6), loc=(0, 0), colspan=2)
ax2 = plt.subplot2grid((2, 6), (0, 2), colspan=2)
ax3 = plt.subplot2grid((2, 6), (0, 4), colspan=2)
ax4 = plt.subplot2grid((2, 6), (1, 1), colspan=2)
ax5 = plt.subplot2grid((2, 6), (1, 3), colspan=2)
复制代码

布局调整

在排列子图的过程当中,可能出现:orm

  • 坐标轴遮挡:使用tight_layout()设置间距,其中pad表示总体轮廓间距,w_pad表示子图水平间距,h_pad表示子图竖直间距;
  • 图像密集:使用set_size_inches()设置图像长宽的具体尺寸(英寸);

即:cdn

plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)
fig = plt.gcf()
fig.set_size_inches(10, 8)
复制代码

这样,子图就能够优雅地排列在一块儿了。


specgram

连续信号推荐使用specgram()展现,即光谱图(spectrogram)。

参数:

  • x:信号连续值列表;
  • Fs:信号帧率;

即:

axes[0, 0].specgram(x=y, Fs=sr)  # 光谱图
axes[0, 0].set_title('std')
复制代码

set_title()用于设置图像的标题。

光谱图

连续信号不推荐使用线图展现,由于在信号中,通常含有帧率,即每秒信号数,而使用线图展现,就会忽略帧率信息,没法体现波形的类似性。


pcolormesh

二维特征推荐使用pcolormesh()展现。除此以外,类似的展现形式:

  • contourf:等高线,与pcolormesh相似,边界较为模糊;
  • imshow:图像模式,支持模糊处理,自适应宽高须要设置aspect的“auto”属性;

axes[0, 0].pcolormesh(df1)
axes[0, 1].contourf(df2)
axes[1, 0].imshow(df2, interpolation='bicubic', aspect='auto')
axes[1, 1].axis('off')
复制代码

axis('off')用于关闭子图。

pcolormesh

二维特征不推荐使用散点图,由于散点图的展现区域较小,对比效果较差。


样式加强

seaborn是Matplotlib的颜色和样式扩展。

使用方式:在plt绘制以前,经过seaborn声明其余的展现样式。

import seaborn as sns

sns.set(style='ticks', palette='Set2')
复制代码

颜色集

Matplotlibcolors,参考


直方图

标准直方图的绘制,输入数据hist_data是列表数据。

def plot_hist(hist_data):
    """ 绘制直方图 :param hist_data: 直方图数据 :return: 展现图 """
    hist_data = np.asarray(hist_data)
    sns.set(style='ticks', palette='Set2')
    fig, aux = plot.subplots(ncols=1, nrows=1)
    aux.hist(hist_data, bins=50, facecolor='magenta', alpha=0.75)
    plot.show()
复制代码

对于坐标轴X(或Y):

  • set_xlabel设置标签;
  • set_xlim设置坐标值的范围
  • set_xticks设置坐标值的粒度;

注意:坐标值的范围(lim)与粒度(ticks)尽可能统一。

aux.set_xlabel("sec")
aux.set_ylabel("num")
min_x, max_x = 8, 22
aux.set_xlim([min_x, max_x])
aux.set_xticks(range(min_x, max_x, 1))
复制代码

Hist


欢迎Follow个人GitHub:https://github.com/SpikeKing

By C. L. Wang @ 美图云事业部

OK, that's all!

相关文章
相关标签/搜索