Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to create bar chart catch-up animation

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use Python to create a bar chart to catch up animation, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Preface

Animation is a good way to make visualization more attractive and user attractive. It helps us present data visualization in a meaningful way. Python helps us create animation visualization using the existing powerful Python libraries. Matplotlib is a very popular data visualization library, which is usually used for graphical representation of data and animation using built-in functions.

There are two ways to create an animation using Matplotlib:

Use the pause () function

Use the FuncAnimation () function

Method 1: use the pause () function

The pyplot module of the matplotlib library in the pause () is functionally used to pause the reference interval seconds for the parameter. Considering the following example, we will use matplotlib to create a simple linear graph and display the animation in it:

Create 2 arrays X and Y and store values from 1 to 100.

Use the plot () function to draw X and Y.

Add the pause () function at appropriate intervals

Run the program and you will see the animation.

Python

From matplotlib import pyplot as plt x = [] y = [] for i in range (100): x.append (I) y.append (I) # mentions x and y restrictions to define their range plt.xlim (0100) plt.ylim (0100) # drawing plt.plot (x, y, color = 'green') plt.pause (0) plt.show ()

Output:

Similarly, you can use the pause () function to create animations in various drawings.

Method 2: use the FuncAnimation () function

The FuncAnimation () function does not create the animation itself, but instead creates the animation from a series of graphics we pass.

Syntax: FuncAnimation (figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True

* * kwargs)

Now you can use the FuncAnimation function to animate many types of things:

Linear graph animation

In this example, we will create a simple linear graph that will show an animation of a line. Similarly, with FuncAnimation, we can create many types of animated visual representations. We just need to define our animation in a function and pass it to FuncAnimation with the appropriate parameters.

Python

From matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimationimport numpy as np x = [] y = [] figure, ax = plt.subplots () # set limits on x and y axes ax.set_xlim (0,100) ax.set_ylim (0,12) # draw a single figure line, = ax.plot (0 0) def animation_function (I): x.append (I * 15) y.append (I) line.set_xdata (x) line.set_ydata (y) return line, animation = FuncAnimation (figure, func = animation_function, frames = np.arange (0,10,0.1), interval = 10) plt.show ()

Output:

Bar chart catch-up animation in Python

In this example, we will create a simple bar graph animation that will show the animation of each bar.

Python

From matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimation, writersimport numpy as npplt.rcParams ['font.sans-serif'] = [' Microsoft YaHei'] fig = plt.figure (figsize = (7je 5)) axes = fig.add_subplot (1Jing 1) axes.set_ylim (0300) palette = ['blue',' red', 'green',' darkorange', 'maroon',' black'] y1, y2, y3, y4, y5, y6 = [] [], [], [] def animation_function (I): Y1 = Iy2 = 6 * Iy3 = 3 * Iy4 = 2 * Iy5 = 5 * Iy6 = 3 * I plt.xlabel ("country") plt.ylabel ("national GDP") plt.bar (["India", "China", "Germany") "USA", "Canada", "UK"], [y1, y2, y3, y4, y5, y6], color = palette) plt.title ("bar animation") animation = FuncAnimation (fig, animation_function, interval = 50) plt.show ()

Output:

Scatter plot animation in Python:

In this example, we will use random functions to animate the scatter chart in python. We will traverse the animation_func and plot the random values of the x and y axes as we iterate.

From matplotlib import pyplot as pltfrom matplotlib.animation import FuncAnimationimport randomimport numpy as npx = [] y = [] colors = [] fig = plt.figure (figsize= (7Magne5)) def animation_func (I): x.append (random.randint (0100)) y.append (random.randint (0100)) colors.append (np.random.rand (1) area = random.randint (0Magne30) * random.randint (0Magne30) plt.xlim ( 0100) plt.ylim (0100) plt.scatter (x Y, c = colors, s = area, alpha = 0.5) animation = FuncAnimation (fig, animation_func, interval = 100) plt.show ()

Output:

Horizontal movement of bar chart catch-up

Here, we will use the highest population in the urban data set to draw a bar chart competition.

Different cities will have different bar charts, and bar chart pursuit will be iterated from 1990 to 2018.

I chose the country with the highest city from the most populous data set.

The dataset you need can be downloaded here: city_populations

Python

Import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.ticker as tickerfrom matplotlib.animation import FuncAnimation plt.rcParams ['font.sans-serif'] = [' Microsoft YaHei'] df = pd.read_csv ('city_populations.csv', usecols= [' name', 'group',' year', 'value']) colors = dict ([' India','Europe','Asia', 'Latin America','Middle East']) 'North America','Africa'], [' # adb0ff','# ffb3ff','# 90d595','# e48381','# aafbff','# f7bb5f' ) group_lk = df.set_index ('name') [' group'] .to_dict () def draw_barchart (year): dff = df [df ['year'] .eq (year)] .sort _ values (by='value', ascending=True) .tail (10) ax.clear () ax.barh (dff [' name'] Dff ['value'], color= [for x in dff [' name']]) dx = dff ['value'] .max () / 200 for I, (value, name) in enumerate (zip (dff [' value'], dff ['name'])): ax.text (value-dx, I, name Size=14, weight=600, ha='right', va='bottom') ax.text (value-dx, iMur.25, group_lk [name], size=10, color='#444444', ha='right', va='baseline') ax.text (value+dx, I, f'{value:,.0f}', size=14 Ha='left', va='center') ax.text (1,0.4, year, transform=ax.transAxes, color='#777777', size=46, ha='right', weight=800) ax.text (0,1.06, 'Population (thousands)', transform=ax.transAxes, size=12, color='#777777') ax.xaxis.set_major_formatter (ticker.StrMethodFormatter ('{x: .0f}') ax.xaxis.set_ticks_position ('top') ax.tick_params (axis='x', colors='#777777', labelsize=12) ax.set_yticks ([]) ax.margins (0,0.01) ax.grid (which='major', axis='x', linestyle='-') ax.set_axisbelow (True) ax.text (0,1.12,' the world's most populous city from 1500 to 2018' Transform=ax.transAxes, size=24, weight=600, ha='left') ax.text (1,0,'by haiyong.site | Sea hold', transform=ax.transAxes, ha='right', color='#777777', bbox=dict (facecolor='white', alpha=0.8, edgecolor='white') plt.box (False) plt.show () fig, ax = plt.subplots (figsize= (15,8) animator = FuncAnimation (fig, draw_barchart) Frames = range (1990, 2019) plt.show ()

Output:

Thank you for reading this article carefully. I hope the article "how to create a bar chart to catch up animation with Python" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report