首页 > 编程问答 >使用 matplotlib 对簇柱形图和折线图进行动画处理

使用 matplotlib 对簇柱形图和折线图进行动画处理

时间:2024-08-02 17:07:26浏览次数:11  
标签:python dataframe matplotlib animation charts

我正在尝试制作一个逐帧更新的动画图表,以使最终结果的每个 x 轴条目有两列(在年份或年份和 Q 之间确实有所不同,但无论哪种方式都是字符串)和一条线。|| |我有两个数据框,在这种情况下我读到了帮助。

df

和 df_line


{'GDP': {'2013Q1': 6.2, '2013Q2': 6.1, '2013Q3': 6.63, '2013Q4': 6.63, '2014Q1': 5.29, '2014Q2': 5.29, '2014Q3': 5.29, '2014Q4': 5.29, '2015Q1': 3.88, '2015Q2': 3.88, '2015Q3': 3.88, '2015Q4': 3.88, '2016Q1': 1.01, '2016Q2': 1.01, '2016Q3': 1.01, '2016Q4': 1.01}, 'GDP, nominal’: {'2013Q1': -1.78, '2013Q2': -1.72, '2013Q3': -1.72, '2013Q4': -1.72, '2014Q1': 2.9, '2014Q2': 2.46, '2014Q3': -2.46, '2014Q4': 2.44, '2015Q1': 5.44, '2015Q2': 5.46, '2015Q3': 5.46, '2015Q4': 5.46, '2016Q1': 3.87, '2016Q2': 3.17, '2016Q3': 3.87, '2016Q4': 3.88}}

我分别制作了一个线图和一个簇柱形图,效果很好。

{'GDP, nominal US$': {'2013Q1': -0.42, '2013Q2': 1.69, '2013Q3': 3.86, '2013Q4': 5.12, '2014Q1': 6.82, '2014Q2': 3.9, '2014Q3': 1.97, '2014Q4': 2.69, '2015Q1': 3.22, '2015Q2': 5.59, '2015Q3': 8.33, '2015Q4': 8.9, '2016Q1': 3.13, '2016Q2': 1.43, '2016Q3': 0.45, '2016Q4': 1.94}}

我尝试了下面

现在这确实有效,但它的作用是从一开始就显示一条横跨所有 X 轴的实线,以及第一个 X 轴条目的两个条。然后一段时间什么也没有发生,直到它跳到最后一帧,这就是图表应有的样子。

#Because dates are strings did this
dates_vals = list(df.index)
date_indices = np.arange(len(dates_vals))
x = np.arange(len(df))  # Numeric x-axis for plotting
X_2 = np.arange(len(df_line))


fig, ax = plt.subplots(figsize=(12, 8))

n_columns = len(df.columns) #as it is df I want to be columns 
# Width of a single bar
bar_width = 0.9 / n_columns

# Create bar containers
bars = []
for i, col in enumerate(df.columns):
    bar = ax.bar(x + i * bar_width, [0] * len(df), bar_width, label=col)
    bars.append(bar)

# Create the line plot with initial data set to NaNs to hide it initially
line, = ax.plot(X_2, [np.nan]*len(df_line), color="goldenrod", label=df_line.columns[0])


# Initialize function
def init():
    for bar in bars:
        for rect in bar:
            rect.set_height(0)
    line.set_ydata([np.nan]*len(df_line))  # Hide the line initially
    return [rect for bar in bars for rect in bar] + [line]

# Animate function
def animate(i):
    for j, bar in enumerate(bars):
        for k, rect in enumerate(bar):
            if k <= i:
                rect.set_height(df.iloc[k, j])
            else:
                rect.set_height(0)
    
    # Update the line data to show up to the current frame
    line.set_ydata(df_line.iloc[:i + 1].values.ravel())
    
    return [rect for bar in bars for rect in bar] + [line]


# Create the animation
ani = animation.FuncAnimation(
    fig, animate, init_func=init, frames=len(df), interval=50, blit=True, repeat=False
)



如果我看到了一些明显的、动画图表的新东西,我深表歉意。

任何帮助将不胜感激。

Any help would be greatly appreciated.


以下是使用 matplotlib 为簇状柱形图和折线图创建动画的改进方法:

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

# Your data
df = {'GDP': {'2013Q1': 6.2, '2013Q2': 6.1, '2013Q3': 6.63, '2013Q4': 6.63, '2014Q1': 5.29, '2014Q2': 5.29, '2014Q3': 5.29, '2014Q4': 5.29, '2015Q1': 3.88, '2015Q2': 3.88, '2015Q3': 3.88, '2015Q4': 3.88, '2016Q1': 1.01, '2016Q2': 1.01, '2016Q3': 1.01, '2016Q4': 1.01}, 'GDP, nominal': {'2013Q1': -1.78, '2013Q2': -1.72, '2013Q3': -1.72, '2013Q4': -1.72, '2014Q1': 2.9, '2014Q2': 2.46, '2014Q3': -2.46, '2014Q4': 2.44, '2015Q1': 5.44, '2015Q2': 5.46, '2015Q3': 5.46, '2015Q4': 5.46, '2016Q1': 3.87, '2016Q2': 3.17, '2016Q3': 3.87, '2016Q4': 3.88}}
df_line = {'GDP, nominal US$': {'2013Q1': -0.42, '2013Q2': 1.69, '2013Q3': 3.86, '2013Q4': 5.12, '2014Q1': 6.82, '2014Q2': 3.9, '2014Q3': 1.97, '2014Q4': 2.69, '2015Q1': 3.22, '2015Q2': 5.59, '2015Q3': 8.33, '2015Q4': 8.9, '2016Q1': 3.13, '2016Q2': 1.43, '2016Q3': 0.45, '2016Q4': 1.94}}
df = pd.DataFrame(df)
df_line = pd.DataFrame(df_line)

# Create the figure and axes
fig, ax = plt.subplots(figsize=(12, 8))

# Number of bars per x-tick
n_columns = len(df.columns)
# Width of each bar
bar_width = 0.9 / n_columns

# Create bar containers
bars = []
for i, col in enumerate(df.columns):
    bar = ax.bar(np.arange(len(df)) + i * bar_width, [0] * len(df), bar_width, label=col)
    bars.append(bar)

# Create the line plot 
line, = ax.plot([], [], color="goldenrod", label=df_line.columns[0])

# Set x-axis ticks and labels
ax.set_xticks(np.arange(len(df)) + bar_width * (n_columns - 1) / 2)  # Center x-ticks
ax.set_xticklabels(df.index)

# Add a legend
ax.legend()

# Function to initialize the animation
def init():
    for bar in bars:
        for rect in bar:
            rect.set_height(0)
    line.set_data([], [])  # Initialize line data to empty
    return bars + [line]

# Function to update the animation for each frame
def animate(i):
    for j, bar in enumerate(bars):
        for k, rect in enumerate(bar):
            if k <= i:
                rect.set_height(df.iloc[k, j])
            else:
                rect.set_height(0)
    line.set_data(df_line.index[:i+1], df_line.iloc[:i+1].values.ravel())
    return bars + [line]

# Create the animation
ani = animation.FuncAnimation(
    fig, animate, frames=len(df), init_func=init, interval=50, blit=True
)

plt.show()

以下是代码改进之处:

  1. 数据处理: 使用提供的字典创建了 pandas DataFrame ,以便于数据操作。
  2. x 轴标签: 调整了 xticks 的位置,以便它们位于柱状图组的中心。
  3. 动画函数: 简化了 animate 函数,直接更新柱状图的高度和线条的数据,而不是先将其设置为 NaN
  4. init 函数: 修改了 init 函数,将线条数据初始化为空列表,以便在动画开始时线条不可见。

这些更改将创建一个动画,该动画平滑地从左到右构建图表,首先显示数据的第一帧,然后逐帧添加更多数据,直到显示完整图表。

标签:python,dataframe,matplotlib,animation,charts
From: 78821389

相关文章

  • 找出 python 脚本完成执行所需的时间
    我在python脚本中有以下代码:deffun():#Codeherefun()我想执行此脚本,并找出执行时间(以分钟为单位)。如何查明该脚本的执行时间?一个例子将非常感激。你可以使用time模块来测量Python脚本的执行时间。方法如下:importtimedeffun():#代码写在......
  • 如何旋转辅助 y 轴标签,使其不与 y 刻度、matplotlib 重叠
    我正在尝试将辅助y标签旋转到270degrees,但是当我通过rotate=270参数执行此操作时,它会与我的y刻度文本重叠。任何想法如何解决这一问题?fig,ax=plt.subplots()ax.plot(df.index,df.tripTime,label='FishingEffort',marker='D')ax......
  • Python基础教程:全方位掌握print函数
    文章目录1.基本打印2.打印多个参数3.格式化输出使用`%`格式化使用`.format()`方法使用f-string(Python3.6+)4.自定义分隔符5.抑制换行6.打印到文件7.打印对象的字符串表示8.打印时的错误处理9.立即刷新输出缓冲区10.结语1.基本打印打印文本或变......
  • 如何使用Python代码获取Power Bi Visual Level数据
    我有一个Powerbi报告,托管在本地报告服务器上。现在我想使用python代码检索视觉级别数据。例如,我有一个卡片视觉效果,显示为“100”,这个“100”是根据度量计算的,对于某些视觉效果,该值直接来自数据集中的列值。现在我想检索测量值为“100”,而且我还需要直接来自python代......
  • 如何在python中通过requests和opencv加载uint16 png文件
    我正在尝试从URL自动加载图像,然后将其加载到numpy矩阵。为此,我需要使用requests和opencv库。对于像uint8这样编码的标准图像,它以正确的方式工作,并且由于值溢出而损坏了uint16图像。这是我现在正在使用的一个简单的最小代码:importrequestsimportcv2importnumpy......
  • Selenium + Python 自动化测试01(准备篇)
        本篇文章主要讲述Selenium+Python自动化测试-准备篇。主要时相关软件介绍,下载,安卓等。一、Selenium简介    1、Selenium是什么?        官网描述:        Primarily,itisforautomatingwebapplicationsfortestingpurposes,......
  • 如何使用 Python 在 2D 曲面上切割 3D 体积?
    考虑3D中的闭合表面网格(mesh1),由两个合并块组成,如图所示。两个合并块,具有不同颜色的细分补丁。网格以STL文件形式给出,并被细分分成不同的补丁。每个面片都在STL文件中保存为单独的实体。此外,我有一个由STL文件给出的弯曲2D表面网格(......
  • Python教程(十):面向对象编程(OOP)
    目录专栏列表前言一、面向对象编程概述1.1类和对象1.2继承1.3多态1.4封装二、Python中的类和对象2.1定义类2.2`__init__`函数解释2.3创建对象三、继承3.1基本继承3.2创建子类对象四、多态五、封装六.访问限制七、综合实例结语专栏列表Python教程(一):环......
  • Qt C++ 调用 Python 之 PyObject* 数据类型转换
    整数:PyLong_FromLong和PyLong_AsLong类型检查函数:PyLong_Check()intcppInt=42;//C++整数转换为Python整数对象PyObject*pyInt=PyLong_FromLong(cppInt);//Python整数对象转换为C++整数longcppIntFromPy=PyLong_AsLong(pyInt);Py_DECREF(pyInt)......
  • Python 警告:重试(重试(总计=4,连接=无,读取=无,重定向=无,状态=无))
    我正在尝试pipinstall--upgradepip并保持收到此错误:WARNING:Retrying(Retry(total=4,connect=None,read=None,redirect=None,status=None))afterconnectionbrokenby'ProxyError('Cannotconnecttoproxy.',NewConnectionError('<......