How to Create a Violin Plot in Plotly Python

Spread the love

1 . Create a Violin Plot in Plotly Python –

Read a dataset

import pandas as pd

url = "https://raw.githubusercontent.com/bprasad26/lwd/master/data/batting.csv"
df = pd.read_csv(url)
df.head()

A violin plot is a statistical representation of numerical data. It is similar to a box plot, with the addition of a rotated kernel density plot on each side.

To create a violin plot in plotly express, we use the px.violin() method.

import plotly.express as px
fig = px.violin(df, y='Runs')
fig.show()

Multiple Violin Plots –

fig = px.violin(df, y='Runs', x='Team')
fig.show()

You can further segment the data using color parameter.

fig = px.violin(df, y='Runs', x='Team', color='Nationality')
fig.show()

2 . Create a Violin Plot with Plotly Graph objects –

To create a Violin Plot with plotly graph objects, we use the go.Violin() method.

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Violin(y=df['Runs']))
fig.update_layout(yaxis_title="Runs")
fig.show()

Customize the violin plot –

fig = go.Figure()
fig.add_trace(go.Violin(y=df['Runs'], box_visible=True, line_color='black',
                               meanline_visible=True, fillcolor='lightseagreen', opacity=0.6,))
fig.update_layout(yaxis_title="Runs")
fig.show()

Multiple Violin Plot –

indian = df[df['Nationality']=="Indian"]
overseas = df[df['Nationality']=="Overseas"]

fig = go.Figure()
fig.add_trace(go.Violin(y=indian['Runs'], box_visible=True, line_color='black',meanline_visible=True, fillcolor='lightseagreen', 
                        opacity=0.6, name='Indian'))
fig.add_trace(go.Violin(y=overseas['Runs'], box_visible=True, line_color='black',meanline_visible=True, fillcolor='lightseagreen', 
                        opacity=0.6,name='Overseas'))
fig.update_layout(yaxis_title="Runs")
fig.show()

1 . How to install plotly python with pip

2 . How to create a Line Chart with Plotly Python

3 . How to create Scatter plot in Plotly Python

4 . How to create a Bar Chart in Plotly Python

5 . How to create Horizontal Bar Chart in Plotly Python

6 . How to create a Histogram in plotly python

7 . How to Create a Box Plot in Plotly Python

8 . How to create a Pie Chart in Plotly Python

9 . How to create a Dot Plot in Plotly Python

10 . How to Create Heatmap with Plotly Python

11 . How to Create Subplots in Plotly Python

Leave a Reply