Libraries
Let's load libraries that we will need.
Load custom fonts
We will also load in custom fonts we want to use for our plot. The Star Wars themed font "Mandalore" is available for free here.
Option 1: Download and install locally
(On Windows) Once you downloaded and installed a custom font, you can load the font and use it later in your plot.
You would call the fonts using fontproperties=title_font.
Option 2: Load remote font
You can also load a remote font (e.g. a font file saved on Github) - which is what we will do.
Code comes from Chris Holdgraf (see his full guide here).
Dataset
We will use a data from Star Wars dialogues to create a circular bar plot of each line of Anakin in Episode 1 - The Phantom Menace. The data is sourced, cleaned and checked by Jean Wieme. He made all of the data available for Data Viz projects in this Github repository.
The data set for this tutorial is filtered for Anakin as speaker and was cleaned up a little bit (e.g. inconsistent names).
| 271.0 | WATTO | Mel tassa cho-passa | 3 | 1 |
| 274.0 | PADME | Are you an angel? | 4 | 1 |
| 276.0 | PADME | An angel. I've heard the deep space pilots tal... | 46 | 1 |
| 278.0 | PADME | I listen to all the traders and star pilots wh... | 27 | 1 |
| 280.0 | PADME | All mylife. | 2 | 1 |
Basic circular bar plot
Polar charts plot data in a circular layout. Instead of horizontal and vertical axes, it has an angular (x-axis) and radial (y-axis) axis.
In this example, we want to visualise each line of Anakin as a bar in a circular plot and use the number of words per line as the length of each bar.
We already have the number of words in our data set. Before plotting, we now need to calculate the correct angular position for each bar.
We will visualise each line of Anakin as one bar and color them based on the character he talks to.
So we define a color palette to map to our data and also set a main background color.
The colors are inspired by this Pudding article.
We can check the color palette using seaborn.
Now, let's create a simple circular plot.
Not too bad, but could do with some cleaning up and enhancements.
Custom scaling of y-axis
Since we plot bars in a circular plot, the longer the bar it also increases the width of the bar on the outer edges.
We can account for the area size of the bars by adjusting the y-axis as follows. Code sourced from this tutorial by Peter Benie which has a lot more explanations.
We will also format the axis labels and gridlines.
Final chart
Putting all the code together and adding a few more bits.
- Change background color to dark and axis labels + gridlines to white.
- Add text annotations + circle in the center
- Add custom legend
Going further
For more examples of how to create or customize your plots with matplotlib, see the circular bar plot section.