chasingtheinfinite
chasingtheinfinite

Reputation: 53

Creating a Violin Plot and Scatter Plot with a Shared Y-Axis in Plotly

I am trying to create a figure with two subplots of the same data:
1) A violin plot which takes up 1/4 of the figure
2) A scatter plot which fills in the remaining 3/4 of the figure
The two figures should share the y-axis labels.

I managed to create this with Matplotlib, but require an interactive version.
How do I combine a Plotly Violin subplot with a Plotly Scatter subplot in a single figure?

What I have tried thusfar (RANKS and SCORES are the data):

import plotly.figure_factory as ff
import plotly.graph_objs as go
from plotly import tools

fig = tools.make_subplots(rows=1, cols=2, shared_yaxes=True)
vio = ff.create_violin(SCORES, colors='#604d9e')
scatter_trace = go.Scatter(x = RANKS, y = SCORES, mode = 'markers')

# How do I combine these two subplots?

Thank you!

Upvotes: 3

Views: 2350

Answers (1)

Maximilian Peters
Maximilian Peters

Reputation: 31729

Plotly's violin plot is a collection of scatterplots. You can therefore add each one separately to a subplot and add your scatterplot to the other subplot.

enter image description here

import plotly
import numpy as np

#get some pseudorandom data
np.random.seed(seed=42)
x = np.random.randn(100).tolist()
y = np.random.randn(100).tolist()

#create a violin plot
fig_viol = plotly.tools.FigureFactory.create_violin(x, colors='#604d9e')

#create a scatter plot
fig_scatter = plotly.graph_objs.Scatter(
    x=x,
    y=y,
    mode='markers',
)

#create a subplot with a shared y-axis
fig = plotly.tools.make_subplots(rows=1, cols=2, shared_yaxes=True)

#adjust the layout of the subplots
fig['layout']['xaxis1']['domain'] = [0, 0.25]
fig['layout']['xaxis2']['domain'] = [0.3, 1]
fig['layout']['showlegend'] = False

#add the violin plot(s) to the 1st subplot
for f in fig_viol.data:
    fig.append_trace(f, 1, 1)

#add the scatter plot to the 2nd subplot
fig.append_trace(fig_scatter, 1, 2)

plotly.offline.plot(fig)

Upvotes: 2

Related Questions