【问题标题】:How to live update Matplotlib plot on top of a background image?如何在背景图像上实时更新 Matplotlib 图?
【发布时间】:2020-08-08 19:27:32
【问题描述】:

我正在尝试在将数据添加到 CSV 文件时实时更新我的​​ matplotlib 绘图。该地块的地理位置很小,坐标轴由经度和纬度给出。这是我目前所拥有的:

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt

df = pd.read_csv("cayugacoords.txt")
BoundaryBox = [-76.5119, -76.5013, 42.4596, 42.4642]
ruh_m = plt.imread('map.png')
fig, ax = plt.subplots(figsize=(8, 7))

ax.scatter(df.longitude, df.latitude, zorder=1, alpha=1, c='r', s=10)
ax.set_title('Cayuga Lake Shore')
ax.set_xlim(BoundaryBox[0], BoundaryBox[1])
ax.set_ylim(BoundaryBox[2], BoundaryBox[3])
ax.imshow(ruh_m, zorder=0, extent=BoundaryBox, aspect='equal')
plt.show()

这就是我运行代码时显示的内容(左下角的三个点已经在 CSV 文件中): Current plot

下面是单独的背景图片:Cayuga Lake

我希望在将新坐标添加到 CSV 文件时定期更新地图。如何才能做到这一点?我研究了动画工具,但在更新绘图时无法保留地图的背景图像。作为参考,CSV 文件“cayugacoords.txt”如下所示:

longitude,latitude
-76.51,42.46
-76.511,42.46
-76.5105,42.46

谢谢!

【问题讨论】:

  • 能否提供背景图片?
  • @BryceWayne 刚刚在原始帖子中添加了指向背景图片的链接。我会查看您发布的链接,但我可能无法为我的情节指定该答案,该情节也绘制背景图像。谢谢!
  • 我回答了你的问题。如果答案对您有用,请将其标记为正确。

标签: python pandas matplotlib plot


【解决方案1】:

使用ax.collections = [] 提供仅更新背景图像上的点的替代解决方案,该解决方案清除图像上绘制的所有线条。为了演示,我绘制了每帧的每个坐标。

import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.animation as animation

df = pd.read_csv("cayugacoords.txt")
BoundaryBox = [-76.5119, -76.5013, 42.4596, 42.4642]
ruh_m = plt.imread('map.png')
fig, ax = plt.subplots(figsize=(8, 7))

ax.set_title('Cayuga Lake Shore')
ax.set_xlim(BoundaryBox[0], BoundaryBox[1])
ax.set_ylim(BoundaryBox[2], BoundaryBox[3])
ax.imshow(ruh_m, zorder=0, extent=BoundaryBox, aspect='equal')

def animate(nframe):
    ax.collections = []
    points = ax.scatter(df.longitude[nframe], df.latitude[nframe], zorder=1,
                        alpha=1, c='r', s=10)
    return

anim = animation.FuncAnimation(fig, animate, frames=3)

【讨论】:

    【解决方案2】:

    这段代码对我有用。它看起来很hacky,但它确实有效。您可以根据自己的喜好调整time.sleep

    from matplotlib import pyplot as plt
    from IPython.display import clear_output
    import pandas as pd
    import numpy as np
    import time
    %matplotlib inline
    
    ruh_m = plt.imread('map.png')
    BoundaryBox = [-76.5119, -76.5013, 42.4596, 42.4642]
    while True:
        clear_output(wait=True)
        df = pd.read_csv("cayugacoords.txt")
        fig, ax = plt.subplots(figsize=(10, 10))
        ax.scatter(df.longitude, df.latitude, zorder=1, alpha=1, c='r', s=10)
        ax.set_title('Cayuga Lake Shore')
        ax.set_xlim(BoundaryBox[0], BoundaryBox[1])
        ax.set_ylim(BoundaryBox[2], BoundaryBox[3])
        ax.imshow(ruh_m, zorder=0, extent=BoundaryBox, aspect='equal')
        plt.show()
        time.sleep(1E-3)
    

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-31
      • 1970-01-01
      • 2019-11-19
      • 2013-11-02
      相关资源
      最近更新 更多