【问题标题】:plotfile not using correct axes, annotation problemplotfile 没有使用正确的轴,注释问题
【发布时间】:2019-01-28 13:36:12
【问题描述】:

我在使用 matplotlibs plotfile 函数时遇到了一个奇怪的行为。

我想注释一个文件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()

这让我得到了以下看起来很奇怪的图,其中轴标签遍布整个地方,并且注释在错误的(相对于我的数据)位置:

但是,当我使用

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

而不是

fig, ax = plt.subplots()

我得到了我想要的地块一个折旧警告:

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 绘制到哪些轴并避免折旧警告以及将其绘制到正确的轴?我假设这不仅仅是绘图文件的问题,而是所有未直接在轴上调用的绘图类型(不像 ax.scatter, ax.plot,...我不能调用 ax.plotfile

【问题讨论】:

  • 您是否有任何理由使用plotfile 而不是以其他方式读取数据并使用其他绘图功能?
  • @DavidG 在这种情况下没有特殊原因,它在这里的另一个问题中使用过,所以我玩了一下这个功能并遇到了这种行为。

标签: python matplotlib plot axes


【解决方案1】:

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 所说,

注意:plotfile 旨在方便从平面文件中快速绘制数据;它不打算作为使用 pyplot 或 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()

【讨论】:

  • 啊,我错过了文档中的注释!你知道为什么fig = plt.figure(); ax = fig.add_subplot(111) 的行为与fig, ax = plt.subplots() 不同吗?
  • 非常感谢您的详尽解释!
  • 等一下,上面是错误的,两者都使用相同的子图。但是,plt.subplots() 使用更多参数启动子图。因此,稍后对.add_subplot(111) 的内部调用将在其参数上有所不同(即没有其他参数),因此正如警告所解释的那样,将创建一个新的子图。如果您自己使用.add_subplot(111),将使用相同的参数,因此不会创建新的子图。因此,一旦弃用期结束,整个问题将统一,在这种情况下,您将始终在未来的版本中获得第一个行为(添加新的子图)。
猜你喜欢
  • 2012-04-27
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-20
  • 2018-05-09
  • 1970-01-01
相关资源
最近更新 更多