plotly

Plotly.Express.Violin

“Violin plots are a type of plot that allows you to visualize the distribution of numerical data. They are closely similar to box plots, but they include a rotated kernel density plot on each side.

The kernel density plot is mirrored on each side, and the area is filled in, providing a violin-like shape.

Violin plots are less popular than box plots but can be much more suitable in various situations. In this article, we will explore how we can create violin plots using the Plotly express module.”

Function Syntax and Parameter List

The syntax for the plotly.express.violin() function is as shown:

plotly.express.violin(data_frame=None, x=None, y=None, color=None, facet_row=None,

facet_col=None, facet_col_wrap=0, facet_row_spacing=None, facet_col_spacing=None,

hover_name=None, hover_data=None, custom_data=None, animation_frame=None,

animation_group=None, category_orders=None, labels=None,

color_discrete_sequence=None, color_discrete_map=None, orientation=None,

violinmode=None, log_x=False, log_y=False, range_x=None, range_y=None,

points=None, box=False, title=None, template=None, width=None, height=None)

Parameters:

  1. data_frame – specifies the data frame containing the columns used in the plot.
  2. x – sets the values used to position the marks along the x-axis in the cartesian coordinate.
  3. y – defines the values used to position the marks along the y axis in the cartesian coordinate.
  4. color – sets the values used to assign unique colors to the marks of the plot.
  5. box – defines if the box should be plotted inside the violin.
  6. title – sets the title for the figure.
  7. width/height – defines the width and height of the figure in pixels.

Example

The following code shows how to create a basic violin plot.

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

The resulting violin figure is as shown:

To draw the box inside the violin, we can set the box parameter to True as shown:

import plotly.express as px
df = px.data.tips()
fig = px.violin(df, y='total_bill', box=True)
fig.show()

Output:

Example 2

We can also create multiple violin plots as shown:

import plotly.express as px
df = px.data.tips()
fig = px.violin(df, x='sex', y='total_bill', box=True, color='sex')
fig.show()

The resulting plots:

To create grouped violin plot, we can use the code as shown:

import plotly.express as px
df = px.data.tips()
fig = px.violin(df, y='total_bill', box=True, color='sex', violinmode='overlay')
fig.show()

Output:

End

In this article, we explored how to create various types of violin plots using the Plotly Express module.

Happy coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list