本文介绍了使用matplotlib面向对象的界面进行seaborn绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常喜欢以OOP风格使用matplotlib:

I strongly prefer using matplotlib in OOP style:

f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(...)
axarr[1].plot(...)

这使跟踪多个图形和子图变得更加容易.

This makes it easier to keep track of multiple figures and subplots.

问题:如何通过这种方式使用seaborn?或者,如何将此示例更改为OOP样式?如何分辨seaborn绘图功能,例如lmplotFigure还是Axes?

Question: How to use seaborn this way? Or, how to change this example to OOP style? How to tell seaborn plotting functions like lmplot which Figure or Axes it plots to?

推荐答案

这在某种程度上取决于您使用的是哪种Seaborn函数.

It depends a bit on which seaborn function you are using.

seaborn中的绘图功能大致分为两类

The plotting functions in seaborn are broadly divided into two classes

  • 轴级"功能,包括regplotboxplotkdeplot以及许多其他功能
  • 图形级"功能,包括lmplotfactorplotjointplot和另外一个或两个
  • "Axes-level" functions, including regplot, boxplot, kdeplot, and many others
  • "Figure-level" functions, including lmplot, factorplot, jointplot and one or two others

通过采用显式的ax参数并返回Axes对象来标识第一组.如此建议,您可以通过将Axes传递给它们来以面向对象"的方式使用它们:

The first group is identified by taking an explicit ax argument and returning an Axes object. As this suggests, you can use them in an "object oriented" style by passing your Axes to them:

f, (ax1, ax2) = plt.subplots(2)
sns.regplot(x, y, ax=ax1)
sns.kdeplot(x, ax=ax2)

轴级函数仅会绘制在Axes上,否则不会与图形混淆,因此它们可以在面向对象的matplotlib脚本中完美地愉快地共存.

Axes-level functions will only draw onto an Axes and won't otherwise mess with the figure, so they can coexist perfectly happily in an object-oriented matplotlib script.

第二组功能(图级)的特征在于,生成的图可能包含多个轴,这些轴始终以有意义"的方式组织.这意味着功能需要完全控制图形,因此不可能将lmplot绘制到已经存在的图形上.调用该函数总是会初始化图形并将其设置为要绘制的特定图形.

The second group of functions (Figure-level) are distinguished by the fact that the resulting plot can potentially include several Axes which are always organized in a "meaningful" way. That means that the functions need to have total control over the figure, so it isn't possible to plot, say, an lmplot onto one that already exists. Calling the function always initializes a figure and sets it up for the specific plot it's drawing.

但是,一旦您调用lmplot,它将返回 FacetGrid .该对象具有一些对生成的图进行操作的方法,这些方法对图的结构有所了解.它还在FacetGrid.figFacetGrid.axes参数中公开了基础图形和轴阵列. jointplot函数非常相似,但是它使用 JointGrid 对象.因此,您仍然可以在面向对象的上下文中使用这些功能,但是所有自定义操作必须在调用该功能之后进行.

However, once you've called lmplot, it will return an object of the type FacetGrid. This object has some methods for operating on the resulting plot that know a bit about the structure of the plot. It also exposes the underlying figure and array of axes at the FacetGrid.fig and FacetGrid.axes arguments. The jointplot function is very similar, but it uses a JointGrid object. So you can still use these functions in an object-oriented context, but all of your customization has to come after you've called the function.

这篇关于使用matplotlib面向对象的界面进行seaborn绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:23