0

我是 matplotlib/Python 的初学者,我正在构建一个动画散点图。我想在绘图下方放置一个按钮,以便用户可以开始/暂停/恢复动画。这是情节(我知道这是一团糟,仍在努力): 在此处输入图像描述

作为开始,我尝试添加一个名为 Play 的按钮,以在第一次自动执行后重播动画,但我无法理解如何将其定位在情节下方,因为它正在“拖动”所有内容(标题,xlabel , ylabel 等等): 在此处输入图像描述

这是代码:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import mplcursors
from matplotlib.animation import FuncAnimation
from matplotlib.widgets import Slider, Button, RadioButtons

df = pd.read_excel('nations2.xls')
df.head()

uniqueYears = df['Ano'].unique()

font = {'family': 'sans-serif',
    'color':  'black',
    'weight': 'normal',
    'size': 16,
    }  

fig, ax = plt.subplots()

def animate(frames):   
    ax.clear()    
    data = df[df['Ano'] == uniqueYears[frames]]
    ax.scatter(y = data['ExpecVida'],
    x = data['PIBperCapita'],
    s = data['PopX1000']/40000,
    c = data['Regiao'].astype('category').cat.codes,
    cmap = cm.viridis,
    edgecolors = 'none',
    alpha = 0.5)

    ax.set_xlim([0,50000], auto=True)
    ax.set_ylim([0,100], auto=True)

    plt.title('Wealth and Health of Nations', fontsize=18)
    plt.xlabel('GDP per Capita ($)', fontsize=14)
    plt.ylabel('Life Expectancy (years)', fontsize=14)
    plt.grid(color = '#A9A9A9')
    plt.text(2, 0.65, uniqueYears[frames], fontdict=font)

    for i, txt in enumerate(data['Pais']):
        ax.annotate(txt, (data['PIBperCapita'].iat[i], data['ExpecVida'].iat[i]), fontsize = 6)


anim = FuncAnimation(fig, animate, frames=len(uniqueYears),interval = 200, repeat=False)

class Index(object):
ind = 0

def play(self, event):
    FuncAnimation(fig, animate, frames=len(uniqueYears),interval = 200, repeat=False)

callback = Index()
axplay = plt.axes([0.81, 0.05, 0.1, 0.075])
bplay = Button(axplay, 'Play')
bplay.on_clicked(callback.play)
4

0 回答 0