Python Plotnine – Violin plot

In this post we will be creating a Python script that will generate a Violin plot, to do this we will be using the plotnine package which is an implementation of a grammar of graphics in Python.

See the sample of Python code below where we utilize the plotnine package to generate a Violin plot, for the purpose of this example we use pandas to create a DataFrame and generate dummy data for our X and Y axis. We then move on to create our Violin plot and use the ‘display’ function from the ‘IPython.display’ module to display it.

import plotnine
import pandas as pd

df = pd.DataFrame({'x': ['A', 'B', 'A', 'B', 'B', 'A'],
                   'y': [1, 3, 5, 7, 9, 11]})

plot = (plotnine.ggplot(df, plotnine.aes(x='x', y='y'))
        + plotnine.geom_violin()


The above would return the following plot to output.

Python Plotnine - Violin plot

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply