【问题标题】:Matplotlib Object Oriented Code to display inline in the notebookMatplotlib 面向对象的代码在笔记本中显示内联
【发布时间】:2018-01-19 11:22:25
【问题描述】:

关于如何获取此代码的任何想法

# -*- noplot -*-
"""
=============================
The object-oriented interface
=============================

A pure OO (look Ma, no pylab!) example using the agg backend
"""
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from matplotlib.figure import Figure

fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3])
ax.set_title('hi mom')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('volts')

this 的 matplotlib 示例库链接中显示我笔记本中的内嵌图表?

请注意:

  • 我想避免使用 pyplot,因为我试图仅使用他们的“面向对象”库来使用 matplotlib
  • 我可以使用 %matplotlib inline%matplotlib notebook 魔法将基于 pyplot 的绘图以内联方式呈现在我的笔记本中

matplotlib 的这个令人困惑的面向对象 API 不一定是内联渲染。

我应该使用不同的画布吗?

使用 fig.show() 会出现以下错误

AttributeError: 'FigureCanvasAgg' object has no attribute 'manager' Figure.show works only for figures managed by pyplot, normally created by pyplot.figure().

另外,这个特定的画布没有 show 方法。所以我完全不知道如何让这些该死的面向对象的图内联渲染。

【问题讨论】:

标签: python oop matplotlib plot jupyter-notebook


【解决方案1】:

要显示不在 pyplot 中且没有关联的图形管理器的图形,您可以使用IPython.core.display

from IPython.core.display import display
display(fig)


请注意,实际上根本没有理由不使用 pyplot 来创建图形。使用pyplot,代码更简洁,会自动显示。
%matplotlib inline
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3])
ax.set_title('hi mom')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('volts');

【讨论】:

  • 非常感谢!!!我发现使用 pyplot 也更加直观和简洁。你知道为什么 matplotlib 文献推荐使用面向对象的接口(我读作 DO NOT Use pyplot)吗?
  • 据我所知,这是指matlab风格的绘图,您可以在其中调用plt模块中的绘图函数来绘制多种绘图,而无需参考任何图形或轴对象。我相信第二个示例,您仅使用 plt 创建图形和轴对象,然后使用它们各自的方法生成绘图,这是在 matplotlib 中绘图的普遍接受的 OO 方法。
  • 如果您需要专门化 matplotlib 类,这样做的一个原因是:` class Figure_special(matplotlib.figure.Figure): def def __init__(self, **kwargs): super(Fig_pressure_overview, self ).__init__(**kwargs) self.canvas = FigureCanvas(self) self.add_subplot(111) def plot(self, data): # 在这里做一些特殊处理以从数据中获取 x 和 y,# 调整 kwargs 等 self .axes[0].plot(x, y, **kwargs)`
猜你喜欢
  • 1970-01-01
  • 2017-01-25
  • 2015-04-07
  • 2013-10-24
  • 2018-06-11
  • 1970-01-01
  • 2017-05-15
相关资源
最近更新 更多