如何使用 matplotlib 创建动画堆积条形图

问题描述 投票:0回答:1

我一直在尝试使用 matplotlib 创建动画堆积条形图。尽管我已设法为每个堆栈元素设置动画,但输出一次仅显示一个元素。我还能够一次获得一列堆积的条形。但我想要的是为每个堆栈元素设置动画,而不会在下一个元素之前清除显示的元素。如果有人可以提供帮助,将不胜感激。 ps:我尝试了 FuncAnimation 和 ArtistAnimation 都失败了。:( 参考值 镍丁 Animated stacked bar elements

这是我的代码。

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

def bstack(df, title, ylabel, xlabel):
    pp = df.values.tolist()
    fig, ax = plt.subplots()
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    def animate(j):
        axlist = []
        for i in range(j):
            yval = df.iloc[i,:].values.tolist()
            stacklabel = df.iloc[i,:].index.tolist()
            for y in range(len(yval)):
                contain = ax.bar(i,yval[y], bottom = sum(yval[:y]),  label = stacklabel[y])
                axlist.append(contain)
        return axlist
    axlist = animate(df.shape[0])
    anim = animation.ArtistAnimation(fig, axlist, interval=500)
    anim.save("stack.gif", writer='ffmpeg')

df = pd.DataFrame({'col1':[1,2,3,4], 'col2':[4,3,2,1], 'col3':[5,6,7,8]})

bstack(df,"mygif","Myplot","Y-axis")
python matplotlib animation bar-chart stacked-bar-chart
1个回答
0
投票

FuncAnimation

R, C = df.shape
ST = df.stack().to_numpy()
CS = df.T.shift(fill_value=0).cumsum()
CS = np.tile(CS.to_numpy(), (R, 1))

plt.style.use("ggplot")

fig, ax = plt.subplots(
    subplot_kw=dict(
        xlim=(-0.5, R - 0.5),
        ylim=(0, df.sum(axis=1).max() + 1),
        xticks=df.index,
    ), figsize=(7, 3),
)

colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]

def stack(i):
    if i == 0:
        pass # empty frame
    else:
        vals = np.zeros(R)
        vals[(i - 1) // C] = ST[i - 1]
        ax.bar(df.index, vals, bottom=CS[i - 1], fc=colors[(i - 1) % C])

ani = FuncAnimation(fig, stack, frames=len(ST) + 1)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.