【问题标题】:Plot blocks of data in succession连续绘制数据块
【发布时间】:2021-07-20 17:27:46
【问题描述】:

我有一个运行时间数据集,已分解为六个月(1 月 - 6 月)。我想绘制散点图的动画,在 x 轴上显示距离,在 y 轴上显示时间。

我没有任何动画:

plt.figure(figsize = (8,8))

plt.scatter(data = strava_df, x = 'Distance', y = 'Elapsed Time', c = col_list, alpha = 0.7)
plt.xlabel('Distance (km)')
plt.ylabel('Elapsed Time (min)')
plt.title('Running Distance vs. Time')
plt.show()

这给了我:

我想要的是一个动画,它绘制第一个月的数据,然后延迟第二个月,依此类推。

from matplotlib.animation import FuncAnimation
fig = plt.figure(figsize=(10,10))
ax = plt.axes(xlim=(2,15), ylim=(10, 80))

x = []
y = []
scat = plt.scatter(x, y)

def animate(i):
    for m in range(0,6):
        x.append(strava_df.loc[strava_df['Month'] == m,strava_df['Distance']])
        y.append(strava_df.loc[strava_df['Month'] == m,strava_df['Elapsed Time']])
    

FuncAnimation(fig, animate, frames=12, interval=6, repeat=False)

plt.show()

这是我想出的,但它不起作用。有什么建议吗?

【问题讨论】:

    标签: python pandas matplotlib animation


    【解决方案1】:

    animate 函数应该更新通过调用 scat = ax.scatter(...) 创建的 matplotlib 对象,并将该对象作为元组返回。可以使用 xy 值的 nx2 数组调用 scat.set_offsets() 来更新位置。颜色可以用scat.set_color() 更新,带有颜色列表或数组。

    假设 col_list 是一个颜色名称或 rgb 值的列表,代码可能如下所示:

    import matplotlib.pyplot as plt
    from matplotlib.animation import FuncAnimation
    import pandas as pd
    import numpy as np
    
    strava_df = pd.DataFrame({'Month': np.random.randint(0, 6, 120),
                              'Distance': np.random.uniform(2, 13, 120),
                              'Color': np.random.choice(['blue', 'red', 'orange', 'cyan'], 120)
                              })
    strava_df['Elapsed Time'] = strava_df['Distance'] * 5 + np.random.uniform(0, 5, 120)
    
    fig = plt.figure(figsize=(10, 10))
    ax = plt.axes(xlim=(2, 15), ylim=(10, 80))
    
    scat = ax.scatter([], [], s=20)
    
    def animate(i):
         x = np.array([])
         y = np.array([])
         c = np.array([])
         for m in range(0, i + 1):
              x = np.concatenate([x, strava_df.loc[strava_df['Month'] == m, 'Distance']])
              y = np.concatenate([y, strava_df.loc[strava_df['Month'] == m, 'Elapsed Time']])
              c = np.concatenate([c, strava_df.loc[strava_df['Month'] == m, 'Color']])
         scat.set_offsets(np.array([x, y]).T)
         scat.set_color(c)
         return scat,
    
    anim = FuncAnimation(fig, animate, frames=12, interval=6, repeat=False)
    plt.show()
    

    【讨论】:

    • 当我在 Jupyter Notebook 中运行此代码时,我没有得到任何输出。我错过了什么吗?
    • 您可能需要%matplotlib notebook 而不是%matplotlib inline 来获得“交互式”内联图而不仅仅是图像。见 a.o. this post 和那里的链接。根据您的环境和 matplotlib 版本,情况可能会有所不同。文档可能会令人困惑。
    猜你喜欢
    • 1970-01-01
    • 2021-01-14
    • 2022-09-23
    • 2017-06-20
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多