3

How can I create a violin plot that encloses individual data points?

The code below displays the violin and the individual data points next to each other; however, rather than next to each other I want the violin to enclose the points (magenta arrow)?

import plotly.express as px

df = px.data.tips()
fig = px.violin(df, y="total_bill", box=False, # draw box plot inside the violin
                points='all', # can be 'outliers', or False
               )
fig.show()

Violin plot

hans
  • 323
  • 1
  • 14

1 Answers1

5

You can achieve this using plotly graph_objects. You have to set the pointpos attribute which sets the position of the sample points in relation to the violins. If "0", the sample points are places over the center of the violins. (https://plotly.com/python/reference/violin/)

import plotly.express as px
import plotly.graph_objects as go

df = px.data.tips()

### define the chart
data = go.Violin(y=df['total_bill'], points='all', pointpos=0)

### assign the chart to the figure
fig = go.Figure(data=data)

### show the plot
fig.show()

enter image description here

Shaunak Sen
  • 548
  • 3
  • 8