python数据python可视化Python

python模块Proplot :高级分析绘图

2021-07-15  本文已影响0人  单细胞空间交响乐

Proplot对matplotlib进行了高度的封装,是一个高级绘图工具,其功能相当强大!而且融和了cartopybasemapxarraypandas。看到这里这应该就是我一直想要的绘图工具了!

图片 图片

如果你满足以下条件,那么Proplot是非常适合你的:

•经常绘图,而且包含很多复杂的子图•经常需要对图进行标注和美化•几乎每天都要创建新的图形
Proplot列出了matplotlib的很多不友好的方面,并通过封装来解决这些问题,提供更友好的交互方式。
更少的代码,更多的图
引入format方法去除了繁琐的图形设置问题,使用更少的代码,高度自定义图形。

示例

Proplot

import proplot as plot
import proplot as plot
f, axs = plot.subplots(ncols=2)
axs.format(linewidth=1, color='gray')
axs.format(xticks=20, xtickminor=True, xlabel='x axis', ylabel='y axis')

matplotlib

import matplotlib.ticker as mticker
from matplotlib import rcParams
rcParams['axes.linewidth'] = 1
rcParams['axes.color'] = 'gray'
fig, axs = plt.subplots(ncols=2)
for ax in axs:
   ax.xaxis.set_major_locator(mticker.MultipleLocator(10))
   ax.tick_params(width=1, color='gray', labelcolor='gray')
   ax.tick_params(axis='x', which='minor', bottom=True)
   ax.set_xlabel('x axis', color='gray')
   ax.set_ylabel('y axis', color='gray')
plt.style.use('default')  # restore

类构造函数

通过类构造函数对类名较长,书写不友好的类进行了封装注册,并提供关键词参数进行自定义。
自动化维度和图形间距
添加新的设置选项控制图形的维度和间距,以更好的解决多子图所带来的图形间距问题。比自带的tightlayout更友好。
去除冗余信息 matplotlib的子图share参数可以让子图共享轴,但是对于轴的标签、legend和colorbar等信息却无法进行处理,Proplot引入了新的Figurecolorbarlegend`方法处理这种情况,使多子图绘图更简洁。
设置外部colorbarlegend matplotlib中为多个子图设置colorbarlegend时是非常麻烦的,尤其是需要自定义位置时。Proplot引入了新的框架处理此类问题。
import proplot as plot
import numpy as np
plot.rc.cycle = '538'
labels = ['a', 'bb', 'ccc', 'dddd', 'eeeee']
f, axs = plot.subplots(ncols=2, span=False, share=1, axwidth=2)
hs1, hs2 = [], []

# On-the-fly legends
state = np.random.RandomState(51423)
for i, label in enumerate(labels):
    data = (state.rand(20) - 0.45).cumsum(axis=0)
    h1 = axs[0].plot(
        data, lw=4, label=label, legend='ul',
        legend_kw={'order': 'F', 'title': 'column major'}
    )
    hs1.extend(h1)
    h2 = axs[1].plot(
        data, lw=4, label=label, legend='r', cycle='Set3',
        legend_kw={'ncols': 1, 'frame': False, 'title': 'no frame'}
    )
    hs2.extend(h2)

# Outer legends
ax = axs[0]
ax.legend(
    hs1, loc='b', ncols=3, title='row major', order='C',
    facecolor='gray2'
)
ax = axs[1]
ax.legend(hs2, loc='b', ncols=3, center=True, title='centered rows')
axs.format(xlabel='xlabel', ylabel='ylabel', suptitle='Legend formatting demo')
图片

subplot容器类

matplotlib的subplots绘制超过1行1列的图形时返回2维数组,1行1列的图形返回1维数组,单个图形则返回Axes实例。Proplot通过封装进行了更改,尤其方便当所有的子图需要统一参数设置时,非常方便。当然也可以对每个子图进行自定义。
import proplot as plot
import numpy as np
state = np.random.RandomState(51423)
f, axs = plot.subplots(ncols=4, nrows=4, axwidth=1.2)
axs.format(
    xlabel='xlabel', ylabel='ylabel', suptitle='Subplot grid demo',
    grid=False, xlim=(0, 50), ylim=(-4, 4)
)

# Various ways to select subplots in the subplot grid
axs[:, 0].format(color='gray7', facecolor='gray3', linewidth=1)
axs[0, :].format(color='red', facecolor='gray3', linewidth=1)
axs[0].format(color='black', facecolor='gray5', linewidth=1.4)
axs[1:, 1:].format(facecolor='gray1')
for ax in axs[1:, 1:]:
    ax.plot((state.rand(50, 5) - 0.5).cumsum(axis=0), cycle='Grays', lw=2)
图片
新的及改进后的绘图方法
matplotlib默认的设置画图是真的难看,pandasxarrayseaborn都进行改进,Proplot则将这些改进又进行了进一步封装优化。
import proplot as plot
import numpy as np

# Pcolor plot with and without distinct levels
f, axs = plot.subplots(ncols=2, axwidth=2)
state = np.random.RandomState(51423)
data = (state.normal(0, 1, size=(33, 33))).cumsum(axis=0).cumsum(axis=1)
axs.format(suptitle='Pcolor plot with levels')
for ax, n, mode, side in zip(axs, (200, 10), ('Ambiguous', 'Discernible'), 'lr'):
    ax.pcolor(data, cmap='spectral', N=n, symmetric=True, colorbar=side)
    ax.format(title=f'{mode} level boundaries', yformatter='null')
图片

Xarraypandas整合

传递xarraypandas数据结构给matplotlib进行绘图时,这些数据结构的元数据信息会丢失。如果要保留元数据,只能使用xarraypandas数据结构自身的绘图函数。而Proplot对这些函数进行了封装,可以更加友好的调用。

Cartopybasemap整合

这里就碰到两个工具各自的痛点了。Cartopy虽然和axes结合的比较好,但是代码冗长,而basemap则单独创建了新的对象,而不是原始的axes实例。
而且这两个工具都要提供地图投影,选择地图投影又是让人非常头疼的事。因为地理图形数据通常存储在经纬度坐标中。ProplotCartopyBasemap整合到了ProjAxes format方法中。

basemap的开发2020年之后将终止。目前Cartopy还存在一些缺点,比如标注坐标标签等问题,物理地图尺度、添加背景图等。一旦这些问题结局了,Proplot将移除basemap

  import proplot as plot
import numpy as np
  offset = -40
  x = plot.arange(offset, 360 + offset-1, 60)
  y = plot.arange(-60, 60+1, 30)
  state = np.random.RandomState(51423)
  data = state.rand(len(y), len(x))

  # Same figure with and without "global coverage"
  titles = ('Geophysical data demo', 'Global coverage demo')
  for globe in (False, True,):
      f, axs = plot.subplots(
          ncols=2, nrows=2, axwidth=2.5,
          proj='kav7', basemap={(1, 3): False, (2, 4): True})
      for i, ax in enumerate(axs):
          cmap = ('sunset', 'sunrise')[i % 2]
          if i < 2:
              m = ax.contourf(x, y, data, cmap=cmap, globe=globe, extend='both')
              f.colorbar(
                  m, loc='b', span=i+1, label='values',
                  tickminor=False, extendsize='1.7em'
              )
          else:
              ax.pcolor(x, y, data, cmap=cmap, globe=globe, extend='both')
          if globe:
              continue
          ix = offset + np.linspace(0, 360, 20)
          for cmd in (np.sin, np.cos):
              iy = cmd(ix*np.pi/180)*60
              ax.plot(ix, iy, color='k', lw=0, marker='o')
      axs.format(
          suptitle=titles[globe],
          collabels=['Cartopy example', 'Basemap example'],
          rowlabels=['Contourf', 'Pcolor'],
          latlabels='r', lonlabels='b', lonlines=90,
          abc=True, abcstyle='a)', abcloc='ul', abcborder=False
      )
图片

colormap和属性循环

matplotlib中的 ListedColormapLinearSegmentedColormap 着实难用。Proplot提供了更加友好的方法,而且提供了新的方法来创建colormap
•**更智能的`colormap`归一化**

Proplot提供了更方便的函数来处理colormap的归一化以及延伸的问题。

import proplot as plot
import numpy as np
f, axs = plot.subplots(
    [[0, 0, 1, 1, 0, 0], [2, 3, 3, 4, 4, 5]],
    wratios=(1.5, 0.5, 1, 1, 0.5, 1.5), axwidth=1.7, ref=1, right='2em'
)
axs.format(suptitle='BinNorm color-range standardization')
levels = plot.arange(0, 360, 45)
state = np.random.RandomState(51423)
data = (20*(state.rand(20, 20) - 0.4).cumsum(axis=0).cumsum(axis=1)) % 360

# Cyclic colorbar with distinct end colors
ax = axs[0]
ax.pcolormesh(
    data, levels=levels, cmap='phase', extend='neither',
    colorbar='b', colorbar_kw={'locator': 90}
)
ax.format(title='cyclic colormap\nwith distinct end colors')

# Colorbars with different extend values
for ax, extend in zip(axs[1:], ('min', 'max', 'neither', 'both')):
    ax.pcolormesh(
        data[:, :10], levels=levels, cmap='oxy',
        extend=extend, colorbar='b', colorbar_kw={'locator': 90}
    )
    ax.format(title=f'extend={extend!r}')
图片
全局参数设置
Proplot提供了新的参数设置方法rc对象,用更加方便的缩略表示更新图形的全局参数。

物理单位引擎

matplotlib的默认单位是inches,这对于美国以外的用户来说是非常让人困惑的。Proplot引入了物理单位引擎来处理此类问题。

.proplot文件夹

matplotlib很难设计自己的colormap和颜色循环,而且也没有内置的方法保存以便以后使用。此外,使用自定义的.ttc.ttf.otf字体文件也很困难。Proplot则自动添加colormaps、颜色循环和字体文件到.proplot/cmaps.proplot/cycles.proplot/fonts文件夹中。
通过register_cmaps, register_cycles, and register_fonts可以手动加载这些文件,而无需重启Ipython

Python绘图精简实例附代码

如何在论文中画出漂亮的插图

首先看插图

图片

还有源码,我加了详细的注释,应该不难理解

图片 图片 图片

2.正态曲线图

图片

代码:

图片 图片

3.云模型示意图

图片 图片 图片

4. scatter-hist图

图片 图片 图片

5.若干类型的图例

图片

6.热图

图片 图片

效果图如下:

图片 图片

效果如下:

图片

7.为点加标签

图片 图片

8.导入已有图片并进行修饰

图片 图片

9.热度方格图

图片 图片

10. 箱线图

图片 图片

双纵坐标

legend不在一块

图片 图片

legend放一块儿

图片 图片

多个子图共用一个legend

图片 图片

就先介绍这么多了,python画图个人觉得比R要强大很多,感兴趣的可以去安装了!生活很好,等你超越~~

上一篇下一篇

猜你喜欢

热点阅读