When it comes to dynamic charts, the most popular is the dynamic bar chart.

A search for the keyword “data visualization” on site B brings up a number of videos related to dynamic bar charts.

Many of the videos have millions of views, which is amazing.

At present, there are many tools to realize dynamic bar graph on the Internet.

For example, a numeral-visible “Hanabi”, a “Dysprosium numerical chart”, and a foreign website “Flourish”.

But as a Pythoner, of course, you want to learn how to do it in Python.

I’ve seen similar functionality implemented by Matplotlib, Plotly, and Pyecharts before, but the amount of code is a bit too much.

So F recently discovered a library called “Bar Chart Race”, which is arguably the most powerful dynamic visualization package in Python.

Making address:

_https://github.com/dexplo/bar_chart_race_

Document Address:

_https://www.dexplo.org/bar_chart_race/_

Currently, there are two versions: 0.1 and 0.2, with 0.2 adding dynamic graph and Plotly implementing dynamic bar graph.

The library is very good, but there are some problems in the installation.

PyCharm’s Project Interpreter only installs to version 0.1 and is not fully featured.

PIP install bar_chart_race is also only available to version 0.1.

At last, F chose to download the project from GitHub **** and then install it.

Download the package and place the extracted folder in the venv/lib/python3.7/site-packages directory of the project.

In the virtual environment, open the folder and run the following command to complete the installation.

CD your project address /venv/lib/python3.7/site-packages/bar_chart_race-master python setup.py install # Finished processing Dependencies for the bar chart - race = = 0.2.0Copy the code

Once installed, you can import the third-party library.

Import bar_chart_race as BCR # Globally cancel certificate validation if SSL error occurs # import SSL # ssl._create_default_https_context = Ssl._create_unverified_context # Retrieve data df = bcr.load_dataset(' COVID-19 19_tutorial')# print(df) # Generate GIF images bcr.bar_chart_race(df, 'covid19_horiz.gif')Copy the code

A GIF is generated, as follows.

3 lines of Python code to implement, the big guy package library to express admiration ~

Here, because the author has encapsulated the data processing module, only three lines of code are required.

For us, we need to load our own data and process it ourselves, so we have 2 more lines.

The data in the sample is directly provided by the author in the COVID 19_tutorial.csv file in the data folder (available on GitHub).

Through its encapsulated data processing function, get the final data.

In addition, the author also provides many configuration parameters for you to choose.

01 Dynamic bar chart Change the dynamic bar chart

Bar_chart_race (df, 'COvid 19_horiz.gif', orientation='v')Copy the code

02 Sorting mode, default descending order (desc)

Bar_chart_race (df, 'COcovid19_horiz.gif ', sort=' ASC ')Copy the code

03 Limit the number of entries. Set this parameter to a maximum of six entries

Bcr.bar_chart_race (df, 'COcovid19_horiz.gif ', n_bars=6)Copy the code

04 Set fixed categories

Bar_chart_race (df, 'COcovid19_horiz.gif ', fixed_order=['Iran', 'USA', 'Italy', 'Spain', 'Belgium'])Copy the code

05 Fixed the numerical axis so that it does not change dynamically

Bar_chart_race (df, 'COcovid19_horiz.gif ', fixed_max=True)Copy the code

06 Image frame number, default 10 frames, set to 3 frames here, you can find that the image has become a little bit stuck

# Number of frames. The smaller the number, the less fluid it is. The bigger, the smoother. bcr.bar_chart_race(df, 'covid19_horiz.gif', steps_per_period=3)Copy the code

07 set the frame rate to 500ms by default

Bcr. bar_chart_race(df, 'COcovid19_horiz.gif ', steps_per_period=20, period_length=200)Copy the code

08 Set the label time to be added per frame. The default value is False

Bcr.bar_chart_race (df, 'COcovid19_horiz.mp4 ', interpolate_period=True)Copy the code

09 Drawing property Settings

# figSIZE - Sets the canvas size, default (6, 3.5) # dpi- image resolution, default 144 # label_bars- displays the numeric information of the bar graph, default True # period_label- displays the time label information, Default is True # title- Chart title bcr.bar_chart_race(df, 'COVID19_horiz.gif ', figsize=(5, 3), DPI =100, label_bars=False, period_label={'x': .99, 'y': .1, 'ha': 'right', 'color': 'red'}, title='COVID-19 Deaths by Country')Copy the code

10 Set the label text size

# title_size- Title tag text size bcr.bar_chart_race(df, bar_label_size) 'covid19_horiz.gif', bar_label_size=4, tick_label_size=5, title='COVID-19 Deaths by Country', title_size='smaller')Copy the code

11 Global text properties

Bar_chart_race (df, 'COVID 19_horiz.gif', title='COVID 19 Deaths by Country', shared_fontdict={'family': 'Helvetica', 'weight': 'bold', 'color': 'rebeccapurple'})Copy the code

12 bar chart properties, you can set transparency, border, etc

# bar_kwargs- Bar graph attribute bcr.bar_chart_race(df, 'COcovid19_horiz.gif ', bar_kwargs={'alpha':.2,' EC ': 'black', 'lw': 3})Copy the code

13 Set the time format for the date label

# set the date format, the default for '% Y - % m - % d' BCR. Bar_chart_race (df, 'covid19_horiz. GIF, period_fmt =' % % % b - d, Y)Copy the code

14 Change the date label to a value

# set date tag to numeric bcr.bar_chart_race(df.reset_index(drop=True), 'COcovid19_horiz.gif ', interpolate_period=True, period_fmt='Index value - {x:.2f}')Copy the code

15 Add dynamic text, which indicates the total number statistics

# Def summary(values, ranks): total_deaths = int(round(values.sum(), -2)) s = f'Total Deaths - {total_deaths:,.0f}' return {'x': .99, 'y': .05, 's': S, 'ha': 'right', 'size': 8} # Add text bcr.bar_chart_race(df, 'COcovid19_horiz.gif ', period_summary_func=summary)Copy the code

16 Add a vertical bar whose value can be average or quantile

# def func(values, ranks): Return values. Quantile (.9) # add perpendicular-bar Bcr.bar_chart_race (df, 'COVID19_horiz.gif ', spintronic spintronic devices: perpendicular_bar_func=func)Copy the code

17 Set the bar chart color. Default is dark24

Bar_chart_race (df, 'COcovid19_horiz.gif ', cmap='accent')Copy the code

The color of the bar chart is not repeated. The figure above has repeated colors

# Remove duplicate colors bcr.bar_chart_race(df, 'COVID19_horiz.gif ', Cmap ='accent', Filter_column_colors =True)Copy the code

There are some caveats here, such as Chinese configuration and custom color configuration.

Add the following three lines of code to the “_make_chart.py” file of the third-party library.

RcParams ['font. Sans-serif '] = ['SimHei'] #Windows plt.rcparams ['font. Sans-serif '] = ['Hiragino sans GB'] #Mac plt.rcParams['axes.unicode_minus'] = FalseCopy the code

Now add Chinese to the chart to see the result.

Import bar_chart_race as BCR import pandas as pd # read data df = pd.read_csv('yuhuanshui. CSV ', encoding=' UTF-8 ', header=0, encoding=' utF-8 ', Df_result = pd.pivot_table(df, values='number', index=['day'], pivot_table(df, values='number', index=['day'], Columns =['name'], fill_value=0)# print(df_result) # print(df_result) # print(df_result, 'heat. Title =' I'm Yu Huanshui ')Copy the code

Using the data of “Baidu Index” of characters in THE TV series Yuhuanshui.

The details of the file are as follows.

After PivotTable processing, the data is in the same format as the library.

To create a dynamic bar chart with your own data, 5 lines of **** will do.

In addition, you can customize the color by adding color information to the “_colormaps.py” file and reference it by CMAP.

colormaps = {"new_colors": ['#ff812c', '#ff5a5a', '#00c5d2', '#a64dff', '#4e70f0', '#f95dba', '#ffce2b']} 
Copy the code

Use a wave and see if it looks better.

Bcr.bar_chart_race (df_result, 'heat.gif', title=' I am yu Huanui hot list ', cmap='new_colors')Copy the code

Sure enough, it looks good

There are some details of the parameters, we can view the library source code, to understand one or two.

You can obtain the CSV file and related installation packages from the private message bar chart.

Long march always feeling, point a “praise” line.