How To Create Cyberpunk-Styled Seaborn Violin Plots with Minimal Python Code

Author:Murphy  |  View: 25272  |  Time: 2025-03-23 18:17:55

Violin plots are a common data visualisation that combines the power of a boxplot and a density plot into a single plot. This allows us to visualise more information within a single figure. For example, we can view the basic statistics from the boxplot, identify possible outliers, and view the distribution of that data. This can help us understand if the data is skewed or contains multi-modal distributions.

Within my latest series of articles, I have been exploring ways to improve and enhance basic matplotlib figures using various themes, including a cyberpunk style. This style provides a futuristic neon-like appearance to the plots and only requires a couple of lines of code to apply to matplotlib and seaborn figures.

If you want to learn more, you can see how I applied it to matplotlib figures in the article below.

Cyberpunking Your Matplotlib Figures

Within this short tutorial, we will take the basic seaborn violin plot and cyberpunk it.

Importing Libraries and Loading Data

We will start by importing the libraries we will work within this tutorial.

These are matplotlib and seaborn for visualising our data, pandas for loading and storing our data, and mplcyberpunk for applying the cyberpunk theme to the seaborn chart.

import matplotlib.pyplot as plt
import pandas as pd
import mplcyberpunk
import seaborn as sns

After importing the required libraries, the next step we need to carry out is to load our data. This is done using the read_csv() function from pandas and passing in the location of the data file.

The data we are going to be using is a subset of the combined XEEK and Force 2020 Machine Learning competition that was aimed at predicting lithology from well log measurements. Further details of this dataset can be found at the end of the article.

df = pd.read_csv('data/Xeek_Well_15-9-15.csv')
Pandas dataframe containing well log measurements for well 15/19–15. Image by the author.

When we view the dataframe ( df ) we get the above image. We can see that we have a single well's worth of data extending from 485m down to 3200m.

Creating the Seaborn Violin Plots

From the dataframe, we are going to use two columns. The RHOB column, which contains the Bulk Density measurements, and the LITH column, which contains the lithological descriptions.

We can call upon the following code to create the basic violin plot.

We first set the figure size to 10 x 5, which will give us a decent-sized figure to look at, and then we call upon sns.violinplot() and pass in the required parameters.

Python">plt.figure(figsize=(10,5))
sns.violinplot(x='LITH', y='RHOB', data=df)

When we run the above code, we get back the following plot.

Basic seaborn violin plot showing variation in Bulk Density (RHOB) with each lithology. Image by the author.

At first glance, the returned plot looks good and useable, however, we can improve the style using the mplcyberpunk library.

Applying Cyberpunk Style to Seaborn Figures

To apply the cyberpunk style to our plot, all we need to do is add an extra line to the code. This line of code uses a with statement and then calls upon plt.style.context and it allows us to apply the style just to the plot that is being called beneath this line rather than changing the global style for all plots.

with plt.style.context('cyberpunk'):
    plt.figure(figsize=(10,5))
    sns.violinplot(x='LITH', y='RHOB', data=df)

When we run the code above, we will get the following violin plot which has most of the cyberpunk theme applied.

Seaborn violin plot after applying the mplcyberpunk theme. Image by the author.

One of the processes that the mplcyberpunk library should do is change the colours of the violins. However, in our case, this hasn't been applied. But it can easily be fixed.

We need to create a list of the cyberpunk colours to fix it. These colours were extracted from the mplcyberpunk source code, but they can be changed to any colours you want. Remember, if you are going for cyberpunk styling, we would likely use bright neon colours.

In addition to creating a list of colours, we can also sort the order of the violins so that they are in alphabetical order. This is an optional step, but a good one, especially when comparing multiple datasets with the same categories.

my_pal=['#08F7FE', '#FE53BB', '#F5D300', '#00ff41', 'r', '#9467bd', '#de014f']

lith_order = df['LITH'].sort_values().unique()

To apply the colours to the files, we can pass my_pal into the palette parameter for the violin plot.

However, to apply the same colour to the edges/lines of the plots, we need to access collections, which store a list of all the parts of the violin plot.

Within this list, every two consecutive items correspond to one violin: the first is the body of the violin, and the second is the mini box plot.

Therefore we need to account for this in our for loop.

with plt.style.context('cyberpunk'):
    plt.figure(figsize=(15,10))
    g=sns.violinplot(x='LITH', y='RHOB', data=df, palette=my_pal,
                     order=lith_order)

    for i in range(len(g.collections)//2):  
        # divide by 2 because collections include both violin 
        # bodies and the mini box plots
        g.collections[i*2].set_edgecolor(my_pal[i])
        g.collections[i*2].set_alpha(0.8)

When we run the above code, we get back the following plot with our cyberpunk violins.

Cyberpunked seaborn violin plot for different lithologies encountered within a well. Image by the Author.

Now that we are able to control the lines and the colours of our plot, we can make a few final tweaks by changing the alpha of fill to make it slightly brighter and increasing the size of our x and y-axis labels.

with plt.style.context('cyberpunk'):
    plt.figure(figsize=(15,10))

    g=sns.violinplot(x='LITH', y='RHOB', data=df, palette=my_pal,
                     order=lith_order)

    for i in range(len(g.collections)//2):
        g.collections[i*2].set_edgecolor(my_pal[i])
        g.collections[i*2].set_alpha(0.9)

    g.set_ylabel('RHOBnn', fontsize=16)
    g.set_xlabel('nnLithology', fontsize=16)
Cyberpunked seaborn violin plot for different lithologies encountered within a well. Image by the Author.

Summary

The mplcyberpunk library provides a quick and easy way to instantly transform your plots from the default styling to something that has a futuristic appearance.

When creating graphics like this, it is always important to consider your audience and ensure that the message and story you are trying to convey is still clear.

Dataset Used in this Tutorial

Subset of a training dataset used as part of a Machine Learning competition run by Xeek and FORCE 2020 (Bormann et al., 2020). This dataset is licensed under Creative Commons Attribution 4.0 International.

The full dataset can be accessed at the following link: https://doi.org/10.5281/zenodo.4351155.


Thanks for reading. Before you go, you should definitely subscribe to my content and get my articles in your inbox. You can do that here!

Secondly, you can get the full Medium experience and support thousands of other writers and me by signing up for a membership. It only costs you $5 a month, and you have full access to all of the fantastic Medium articles, as well as the chance to make money with your writing.

If you sign up using my link, you will support me directly with a portion of your fee, and it won't cost you more. If you do so, thank you so much for your support.

Tags: Data Science Data Visualization Geoscience Python Seaborn

Comment