python - 对 mpl.figure.Figure 的列表引用不显示绘图
问题描述
我正在尝试处理带有对象的数字列表。不幸的是,从数字列表中绘制似乎存在问题。
请在下面的示例中注释掉该行,您会看到绘图是如何中断的:
import matplotlib as mpl
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, FigureManagerQT
class Test:
def __init__(self):
self.figs = [mpl.figure.Figure(),mpl.figure.Figure()]
self.fig = mpl.figure.Figure()
ax = self.fig.subplots()
ax.plot([1,2],[3,4])
def show(self):
fig = self.fig # works
# fig = self.figs[0] # does not work
canvas = FigureCanvasQTAgg(fig)
figManager = FigureManagerQT(canvas, 0)
a=Test()
a.show()
在其他一些测试中,我发现它可能与破坏对象有关。由于列表是可变对象,因此这可能是连接。我还尝试(不成功)几种解决方法来复制图形对象以进行绘图:我使用了类似于fig = myCopy(self.figs[0])
与pickle-copy组合的东西。
您能否解释一下正在发生的事情以及可能的解决方法?
解决方案
在__init__
中,您将坐标轴指定给该对象self.fig
并绘制到该Axes
对象:
class Test:
def __init__(self):
self.figs = [mpl.figure.Figure(),mpl.figure.Figure()]
self.fig = mpl.figure.Figure()
ax = self.fig.subplots()
ax.plot([1,2],[3,4])
中的图形对象self.figs
没有Axes
附加任何对象,因此它们基本上是空的。结果,你看到的是一个空图:
def show(self):
fig = self.figs[0] # This is a figure with no axes
canvas = FigureCanvasQTAgg(fig)
figManager = FigureManagerQT(canvas, 0)
您的逻辑问题在于,在__init__
方法中绘制数据并没有真正的意义。您的工作流程应该是:
- 初始化
- 图选择
- 阴谋
- 节目
我建议你添加两个方法,select_figure
和plot
,以提高你的图形管理器的整体可用性:
class Test:
def __init__(self):
self.fig = None
self.figures = [mpl.figure.Figure(), mpl.figure.Figure()]
def select_figure(self, index):
self.fig = self.figures[index]
def plot(self, x, y):
ax = self.fig.subplots()
ax.plot(x, y)
def show(self):
canvas = FigureCanvasQTAgg(self.fig)
figManager = FigureManagerQT(canvas, 0)
然后你可以实现我上面描述的工作流程:
test = Test()
test.select_figure(0)
test.plot([1, 2], [3, 4])
test.show()
test.select_figure(1)
test.plot([3, 4], [5, 6])
test.show()
推荐阅读
- php - ActiveMQ - 根据客户端 ID 断开另一个客户端的任何方式?
- javascript - 从 Select 中的 onchange 事件调用 window.print() 时出错
- c++ - 给定一个 3 x 3 矩阵或任何 nxn 矩阵,为什么我的以下函数找不到对角线差异?
- c# - 检查 IEnumerable 中非空值的内容
- python - 逐行求和值并获得达到总数 x % 的列
- rest - Azure Devops API,如何判断代理是否正在运行构建?
- javascript - 如何从 JavaScript 对象中删除与正则表达式匹配的所有属性?
- python - 如何使用 python HL7Apy 正确解析 HL7 消息?
- javascript - 为什么我的函数没有产生预期的结果?
- amazon-web-services - 如何在 Glue 作业中访问 AWS Glue 工作流的运行属性?