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:
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:
- data_frame – specifies the data frame containing the columns used in the plot.
- x – sets the values used to position the marks along the x-axis in the cartesian coordinate.
- y – defines the values used to position the marks along the y axis in the cartesian coordinate.
- color – sets the values used to assign unique colors to the marks of the plot.
- box – defines if the box should be plotted inside the violin.
- title – sets the title for the figure.
- width/height – defines the width and height of the figure in pixels.
Example
The following code shows how to create a basic violin plot.
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:
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:
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:
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!!