plotfile未使用正确的轴,注释问题

2024-04-24 01:29:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用matplotlibsplotfile函数时遇到了一个奇怪的行为。你知道吗

我想对文件text.txt的一个绘图进行注释,它包含:

x
0
1
1
2
3

使用以下代码:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
annot = ax.annotate("Test", xy=(1,1))
plt.plotfile('test.txt', newfig = False)
plt.show()

这使我得到以下奇怪的图,轴标签到处都是,注释在错误的位置(相对于我的数据):

plt.subplots()

但是,当我使用

fig = plt.figure()
ax = fig.add_subplot(111)

而不是

fig, ax = plt.subplots()

我得到了我想要的地块,并且有一个贬值警告: plt.figure()

MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

因此,我认为在一种情况下,plt.plotfile使用以前的轴,也用于生成注释,但这会给我一个警告,而在另一种情况下,它会生成一个新的轴实例(因此没有警告),但也会生成一个带有两个重叠轴的奇怪绘图。你知道吗

现在我想知道两件事:

  1. 根据this answer它们应该互换,为什么我如何声明我的图形和轴会有区别呢?你知道吗
  2. 如何告诉plotfile要打印到哪些轴,如何避免折旧警告以及如何将其打印到正确的轴?我假设这不仅仅是plotfiles的问题,而是所有不能直接在轴上调用的打印类型的问题(不像ax.scatter, ax.plot。。。我不能打电话给ax.plotfile

Tags: andtheinstancetxt警告绘图asfig
1条回答
网友
1楼 · 发布于 2024-04-24 01:29:07

plotfile是一个方便的函数,可以直接打印文件。这意味着它假定不存在先验轴和creates a new one。如果真的有人在场,这可能会导致有趣的行为。但你仍然可以按预期的方式使用它

import matplotlib.pyplot as plt

plt.plotfile('test.txt')
annot = plt.annotate("Test", xy=(1,1))
plt.show()

然而,正如the documentation所说

Note: plotfile is intended as a convenience for quickly plotting data from flat files; it is not intended as an alternative interface to general plotting with pyplot or matplotlib.

因此,一旦您想对图形或轴进行重大更改,最好不要依赖plotfile。类似的功能可以通过

import numpy as np
import matplotlib.pyplot as plt

plt.plot(np.loadtxt('test.txt', skiprows=1))
annot = plt.annotate("Test", xy=(1,1))
plt.show()

与面向对象的方法完全兼容

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
annot = ax.annotate("Test", xy=(1,1))
ax.plot(np.loadtxt('test.txt', skiprows=1))

plt.show()

相关问题 更多 >