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

时间:2019-01-28 13:36:12

标签: python matplotlib plot axes

使用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()

这使我得到以下看起来很奇怪的图,其中整个位置都有轴标签,而注释位于错误的位置(相对于我的数据):

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的问题,还包括不是直接在轴上调用的所有plot类型(与ax.scatter, ax.plot等不同,...我不能调用ax.plotfile

1 个答案:

答案 0 :(得分: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()