Create Stunning Dynamic Bar Chart Races in Python with Just 3 Lines of Code
This tutorial shows how to generate eye‑catching dynamic bar‑chart‑race visualisations in Python using the bar_chart_race library, covering installation challenges, basic usage, GIF/MP4 output, and a wide range of customisation options such as orientation, sorting, colour maps, labels and Chinese text support.
Why dynamic bar charts?
Dynamic bar charts are one of the hottest forms of data visualisation, with many high‑view‑count videos on platforms like Bilibili. Existing tools such as Huaxian "Hanabi", Dijishu "DiShu Chart" and Flourish can create them, but Python developers often prefer a native solution.
Introducing bar_chart_race
The Bar Chart Race library is a powerful Python package that simplifies creating animated bar charts. It can be found on GitHub at https://github.com/dexplo/bar_chart_race with documentation at https://www.dexplo.org/bar_chart_race/ . Two versions exist (0.1 and 0.2); version 0.2 adds dynamic line charts and Plotly‑based bar charts.
Installation
Installation via pip install bar_chart_race only provides version 0.1, which lacks some features. In PyCharm’s Project Interpreter the same limitation appears. The workaround is to download the source from GitHub and install manually:
cd your_project_path/venv/lib/python3.7/site-packages/bar_chart_race-master
python setup.py install
# Installation success messagesAfter manual installation you can import the library normally.
Basic usage – generate a GIF in three lines
import bar_chart_race as bcr
# Load example dataset
df = bcr.load_dataset('covid19_tutorial')
# Create animated GIF
bcr.bar_chart_race(df, 'covid19_horiz.gif')The resulting GIF demonstrates a simple dynamic bar chart.
Customising the chart
The library offers many parameters. Below are common examples:
Orientation : bcr.bar_chart_race(df, 'covid19_horiz.gif', orientation='v') Sorting (default descending, use sort='asc' for ascending)
Number of bars : n_bars=6 Fixed order : specify a list of categories to keep their order.
Fixed maximum axis : fixed_max=True Frames per period (controls smoothness): steps_per_period=3 Period length (ms) : period_length=200 Period summary : define a function returning a dict with text position and content.
Perpendicular bar : supply a function returning a quantile value.
Colour map : cmap='accent' or custom maps.
Remove duplicate colours : filter_column_colors=True Figure size & DPI : figsize=(5,3), dpi=100 Hide bar labels : label_bars=False Custom period label and title styling via dictionaries.
Text size : bar_label_size=4, tick_label_size=5, title_size='smaller' Global font settings for Chinese characters:
plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows
plt.rcParams['font.sans-serif'] = ['Hiragino Sans GB'] # macOS
plt.rcParams['axes.unicode_minus'] = FalseAfter setting the font, Chinese titles and labels render correctly.
Custom colour maps
Define a new colour list in _colormaps.py:
colormaps = {
"new_colors": [
'#ff812c', '#ff5a5a', '#00c5d2', '#a64dff', '#4e70f0', '#f95dba', '#ffce2b'
]
}Then use it with cmap='new_colors' to apply the custom palette.
Real‑world example with custom data
Load a CSV containing Baidu Index data for characters from the TV series “Yu Huan Shui”, pivot it into the required format, and visualise it:
import pandas as pd
import bar_chart_race as bcr
df = pd.read_csv('yuhuanshui.csv', encoding='utf-8', header=0,
names=['name','number','day'])
df_result = pd.pivot_table(df, values='number', index='day',
columns='name', fill_value=0)
bcr.bar_chart_race(df_result, 'heat.gif', title='我是余欢水演职人员热度排行')The final animated chart displays the popularity ranking over time.
Conclusion
The bar_chart_race library provides a concise, flexible way to create animated bar‑chart‑races in Python. With a handful of parameters you can control orientation, sorting, colour schemes, label styles, Chinese text support, and export formats (GIF, MP4). Exploring the source code reveals even more fine‑tuned options.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
