Make Your Charts Great with UTF-8

Author:Murphy  |  View: 23382  |  Time: 2025-03-23 18:22:08
Photo by Le Vu on Unsplash

Python's major graphing libraries make beautiful charts out-of-the-box, but they're designed for exploratory data analysis, professional reports, and scientific articles. They can be a bit dry for consumption by the general public and other non-technical folks.

In this Quick Success Data Science project, we'll look at a way to spice up your graphs using readily available icons that can be treated as text. Specifically, we'll use the popular Plotly Express library to make a bar chart of the theoretical maximum number of squares each chess piece can control at one time (assuming the piece is in the center of an empty board).

To make this a more engaging infographic, we'll decorate the bars with symbols available in the UTF-8 collection of characters.

Example of decorated bars in a bar chart (image by the author)

What is UTF-8?

According to Wikipedia, "UTF-8 is a variable-length character encoding standard used for electronic communication. Defined by the Unicode Standard, the name is derived from Unicode (or Universal Coded Character Set) Transformation Format – 8-bit. UTF-8 is the dominant encoding for the World Wide Web (and internet technologies)."

With UTF-8, every character you may want to use, such as the symbol for pi or the letter "A," is assigned a unique code. Besides familiar text characters, UTF-8 includes icons for all types of things, from smiling faces to jet planes to snails. These icons can be treated as text when annotating Plotly Express charts.

Finding UTF-8 Icons

You can search for UTF-8 icons on this site. Rather than search for each individual chess piece, search for "chess." This will return the page shown below, with a listing of compatible icons.

Results of searching for the Unicode symbol for "chess" (image by the author)

If you click the white knight icon, you'll get the screen below.

Results of clicking on the white knight icon (image by the author)

Here's the fun part. To use this icon, simply highlight and copy the large image. You can then paste this image directly into your Python code, as I'll demonstrate shortly. There's no need to enter the actual UTF-8 code.

The Plotly Express Library

To make the chart, we'll use Plotly Express, a higher-level version of the Plotly graphing library. This library abstracts away much of the drudgery in making plots and lets you easily produce attractive figures with a lot of built-in functionality.

Plotly Express requires Plotly as a dependency. You can install it with either conda or pip.

Here's the conda installation: conda install -c plotly plotly_express

And here's the pip version: pip install plotly


The Code

The following code was run in JupyterLab. It's presented and described by cell.

Importing Libraries

Plotly Express is designed to work well with data in the pandas DataFrame format, so we'll want to import both Plotly Express and pandas. Pandas can be installed with either conda install pandas or pip install pandas.

import pandas as pd
import plotly.express as px

Entering the Data

We'll enter the data into two dictionaries which use the names of the pieces as keys. One will hold the number of squares controlled per piece and one will hold the UTF-8 symbols. We'll merge these on the piece name, so these should be the same in both dictionaries.

Note how you can directly paste the icon from the UTF-8 search page referenced previously. Is that cool or what? You just need to enclose it in single or double quotes as it's treated as a string.

squares = {'King': 8, 
           'Queen': 27, 
           'Rook': 14,
           'Bishop': 13,
           'Knight': 8, 
           'Pawn': 2}

symbols = {'King': '♔', 
           'Queen': '♕', 
           'Rook': '♖',
           'Bishop': '♗',
           'Knight': '♘', 
           'Pawn': '♙'}

df_squares = pd.DataFrame(squares.items(), 
                          columns=['Piece', 'Max Squares'])
df_squares = df_squares.sort_values(by='Max Squares')
df_symbols = pd.DataFrame(symbols.items(), 
                          columns=['Piece', 'Symbol'])
df_merged = df_squares.merge(df_symbols)
df_merged.head(6)
The merged DataFrame (image by the author)

Creating the Chart

Plotly Express makes it easy to generate standard charts such as bar charts, scattergrams, heatmaps, and so on. Here, we'll use the bar() method to make a bar chart. Once you pass the method the DataFrame's name, you just need to provide the column names to access the data in subsequent arguments. This makes for very readable code.

The text argument captures the UTF-8 symbol, which will be placed automatically near the top of each bar. To control the size of the symbol, use the textfont_size argument of the update_traces() method. The marker_color argument refers to the bar color, not the symbol color.

fig = px.bar(df_merged, 
             x='Piece', 
             y='Max Squares',
             height=550,
             text='Symbol')
fig.update_traces(textfont_size=70, marker_color='black')
fig.show()  # optional
The theoretical maximum number of squares each piece can control at one time (image by the author)

As you can see, UTF-8 icons can be treated as regular text when making plots in Plotly Express. This means that you can use them as text annotations and place them anywhere you want. In the example that follows, we place a red smiley face above the Knight bar to demonstrate the process.

# Add annotation:
fig.add_annotation(dict(font=dict(color='red',
                                  size=50),
                                  x=0.39,
                                  y=0.45,
                                  showarrow=False,
                                  text="☺",
                                  textangle=0,
                                  xanchor='left',
                                  xref="paper",
                                  yref="paper"))
fig.show()  # optional
Bar chart with red smiley face posted over the Knight bar (image by the author)

Results

UTF-8 icons let you add a little whimsy to your plots, giving them an "infographics" type of feel. While not necessary or even desired for analytical work or scientific articles, decorating plots in this manner can be beneficial when preparing newsletters, tutorials, annual reports, and other documents aimed at a non-technical audience.


Thanks!

Thanks for reading and please follow me for more Quick Success Data Science projects in the future.

Tags: Data Visualization Plotly Express Plotly Python Utf 8 Visualization

Comment