前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >气象人开发的高级科学绘图库Proplot!

气象人开发的高级科学绘图库Proplot!

作者头像
气象学家
发布2020-03-11 14:08:45
3.2K0
发布2020-03-11 14:08:45
举报
文章被收录于专栏:气象学家气象学家

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

看到这里已经跪了!赶紧去Github follow/star一波!

好了,啥也别说了!请让我趴地上把下面的内容介绍完!

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

•经常绘图,而且包含很多复杂的子图•经常需要对图进行标注和美化•几乎每天都要创建新的图形

Proplot列出了matplotlib的很多不友好的方面,并通过封装来解决这些问题,提供更友好的交互方式。

更少的代码,更多的图

引入format方法去除了繁琐的图形设置问题,使用更少的代码,高度自定义图形。

示例

Proplot

代码语言:javascript
复制
1.import proplot as plot
2.f, axs = plot.subplots(ncols=2)
3.axs.format(linewidth=1, color='gray')
4.axs.format(xticks=20, xtickminor=True, xlabel='x axis', ylabel='y axis')

matplotlib

代码语言:javascript
复制
1.import matplotlib.ticker as mticker
2.from matplotlib import rcParams
3.rcParams['axes.linewidth'] = 1
4.rcParams['axes.color'] = 'gray'
5.fig, axs = plt.subplots(ncols=2)
6.for ax in axs:
7.   ax.xaxis.set_major_locator(mticker.MultipleLocator(10))
8.   ax.tick_params(width=1, color='gray', labelcolor='gray')
9.   ax.tick_params(axis='x', which='minor', bottom=True)
10.  ax.set_xlabel('x axis', color='gray')
11.  ax.set_ylabel('y axis', color='gray')
12.plt.style.use('default')  # restore

类构造函数

通过类构造函数对类名较长,书写不友好的类进行了封装注册,并提供关键词参数进行自定义。

自动化维度和图形间距

添加新的设置选项控制图形的维度和间距,以更好的解决多子图所带来的图形间距问题。比自带的tightlayout更友好。

去除冗余信息

matplotlib的子图share参数可以让子图共享轴,但是对于轴的标签、legend和colorbar等信息却无法进行处理,Proplot引入了新的Figurecolorbarlegend`方法处理这种情况,使多子图绘图更简洁。

设置外部colorbarlegend

matplotlib中为多个子图设置colorbarlegend时是非常麻烦的,尤其是需要自定义位置时。Proplot引入了新的框架处理此类问题。

代码语言:javascript
复制
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通过封装进行了更改,尤其方便当所有的子图需要统一参数设置时,非常方便。当然也可以对每个子图进行自定义。

代码语言:javascript
复制
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则将这些改进又进行了进一步封装优化。

代码语言:javascript
复制
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

代码语言:javascript
复制
  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中的 ListedColormap[1] 和 LinearSegmentedColormap[2] 着实难用。Proplot提供了更加友好的方法,而且提供了新的方法来创建colormap

更智能的colormap归一化

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

代码语言:javascript
复制
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[3], register_cycles[4], and register_fonts[5]可以手动加载这些文件,而无需重启Ipython

就先介绍这么多了,感兴趣的可以去安装了!让我再趴一会!

References

[1] ListedColormap: https://matplotlib.org/api/_as_gen/matplotlib.colors.ListedColormap.html#matplotlib.colors.ListedColormap [2] LinearSegmentedColormap: https://matplotlib.org/api/_as_gen/matplotlib.colors.LinearSegmentedColormap.html#matplotlib.colors.LinearSegmentedColormap [3] register_cmaps: https://proplot.readthedocs.io/en/latest/api/proplot.styletools.register_cmaps.html#proplot.styletools.register_cmaps [4] register_cycles: https://proplot.readthedocs.io/en/latest/api/proplot.styletools.register_cycles.html#proplot.styletools.register_cycles [5] register_fonts: https://proplot.readthedocs.io/en/latest/api/proplot.styletools.register_fonts.html#proplot.styletools.register_fonts

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 气象学家 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • References
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档