如何在不移动标题和标签的情况下定位matplotlib的Button

时间:2018-05-30 19:22:43

标签: python python-3.x matplotlib

我是matplotlib / Python的初学者,我正在构建一个动画散点图。我想在图表下方放置一个按钮,以便用户可以开始/暂停/恢复动画。这是情节(我知道这是一个烂摊子,仍在努力): enter image description here

作为一个开始,我尝试添加一个名为Play的按钮,以便在第一次自动执行后重放动画,但我无法理解如何将它放置在绘图下方,因为它正在“拖动”所有内容(标题,xlabel,ylabel等): enter image description here

以下是代码:

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)

0 个答案:

没有答案