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 we recently discovered a library called “Bar Chart Race,” which is arguably the most powerful dynamic visualization package in Python.
Making address:
_github. Com/dexplo/bar \… _
Document Address:
_www. Dexplo.org/bar\_chart\… _
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.
Finally, I 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
-
# Successful installation
-
# Finished processing dependencies for bar-chart-race==0.2.0
-
Copy the code
Once installed, you can import the third-party library.
-
import bar_chart_race as bcr
-
If an SSL error occurs, certificate verification is cancelled globally
-
# import ssl
-
# ssl._create_default_https_context = ssl._create_unverified_context
-
# Fetch data
-
df = bcr.load_dataset(‘covid19_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
-
Orientation =’v’, histogram is generated
-
bcr.bar_chart_race(df, ‘covid19_horiz.gif’, orientation=’v’)
-
Copy the code
02 Sorting mode, default descending order (desc)
-
# Set the sort mode, ASC – ascending
-
bcr.bar_chart_race(df, ‘covid19_horiz.gif’, sort=’asc’)
-
Copy the code
03 Limit the number of entries. Set this parameter to a maximum of six entries
-
# set the maximum number of items that can be displayed
-
bcr.bar_chart_race(df, ‘covid19_horiz.gif’, n_bars=6)
-
Copy the code
04 Set fixed categories
-
# Select the data of the following 5 countries
-
bcr.bar_chart_race(df, ‘covid19_horiz.gif’, fixed_order=[‘Iran’, ‘USA’, ‘Italy’, ‘Spain’, ‘Belgium’])
-
Copy the code
05 Fixed the numerical axis so that it does not change dynamically
-
# Set the maximum value and fix the axis
-
bcr.bar_chart_race(df, ‘covid19_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
-
Set the total time of 20 frames to 200ms
-
bcr.bar_chart_race(df, ‘covid19_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
-
# output MP4
-
bcr.bar_chart_race(df, ‘covid19_horiz.mp4’, interpolate_period=True)
-
Copy the code
09 Drawing property Settings
-
# figsize- Set canvas size, default (6, 3.5)
-
# dpi- Image resolution, default 144
-
# label_bars- Displays numerical information for the bar graph. Default is True
-
# period_label- Displays 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
-
# bar_label_size- Bar chart label text size
-
# tick_label_size- The text size of the axis label
-
# title_SIZE – Title tag text size
-
bcr.bar_chart_race(df, ‘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
-
# shared_fontdict- Global font attribute
-
bcr.bar_chart_race(df, ‘covid19_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 chart property
-
bcr.bar_chart_race(df, ‘covid19_horiz.gif’, bar_kwargs={‘alpha’: .2, ‘ec’: ‘black’, ‘lw’: 3})
-
Copy the code
13 Set the time format for the date label
-
# set date format to ‘%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 the date label to a numeric value
-
bcr.bar_chart_race(df.reset_index(drop=True), ‘covid19_horiz.gif’, interpolate_period=True, period_fmt=’Index value – {x:.2f}’)
-
Copy the code
15 Add dynamic text, which indicates the total number statistics
-
Set text position, value, size, color, etc
-
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, ‘covid19_horiz.gif’, period_summary_func=summary)
-
Copy the code
16 Add a vertical bar whose value can be average or quantile
-
# Set vertical bar value, quantile
-
def func(values, ranks):
-
return values.quantile(.9)
-
# Add vertical bar
-
bcr.bar_chart_race(df, ‘covid19_horiz.gif’, perpendicular_bar_func=func)
-
Copy the code
17 Set the bar chart color. Default is dark24
-
# Set bar chart color
-
bcr.bar_chart_race(df, ‘covid19_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.
-
# Chinese display
-
plt.rcParams[‘font.sans-serif’] = [‘SimHei’]
-
#Windows
-
plt.rcParams[‘font.sans-serif’] = [‘Hiragino Sans GB’]
-
#Mac
-
plt.rcParams[‘axes.unicode_minus’] = False
-
Copy the code
Now add Chinese to the chart to see the result.
-
import bar_chart_race as bcr
-
import pandas as pd
-
# fetch data
-
df = pd.read_csv(‘yuhuanshui.csv’, encoding=’utf-8′, header=0, names=[‘name’, ‘number’, ‘day’])
-
# Processing data
-
df_result = pd.pivot_table(df, values=’number’, index=[‘day’], columns=[‘name’], fill_value=0)# print(df_result)
-
# Generate images
-
Bcr.bar_chart_race (df_result, ‘heat.gif’, title=’ I am yu Huishuizi hot list ‘)
-
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. PS: If you need Python learning materials, please click on the link below to obtain them
Free Python learning materials and group communication solutions click to join
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.
-
# Use a custom color list
-
Bcr.bar_chart_race (df_result, ‘heat.gif’, title=’ I am yu Huanui hot ranking ‘, 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.
PS: If you need Python learning materials, please click on the link below to obtain them
Click to join the complete code point he gets