Plotly:如何结合 make_subplots() 和 ff.create_distplot()?

Plotly: How to combine make_subplots() and ff.create_distplot()?

使用 plotly 创建多个子图既简单又优雅。考虑以下示例,它并排绘制数据框中的两个系列:

剧情:

代码:

# imports
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# data
np.random.seed(123)
frame_rows = 40
n_plots = 6
#frame_columns = ['V_'+str(e) for e in list(range(1,n_plots+1))]
frame_columns = ['V_1', 'V_2']
df = pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
                  index=pd.date_range('1/1/2020', periods=frame_rows),
                    columns=frame_columns)
df=df.cumsum()+100
df.iloc[0]=100

# plotly setup
plot_rows=1
plot_cols=2
fig = make_subplots(rows=plot_rows, cols=plot_cols)

# plotly traces
fig.add_trace(go.Scatter(x=df.index, y=df['V_1']), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['V_2']), row=1, col=2)


fig.show()

similar objects 替换 go.Scatter() 对象很容易:

剧情:

但我似乎找不到将此设置与 ff.create_distplot() 相结合的方法:

Distplot:

带有 distplot 的代码:

# imports
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# data
np.random.seed(123)
frame_rows = 40
n_plots = 6
#frame_columns = ['V_'+str(e) for e in list(range(1,n_plots+1))]
frame_columns = ['V_1', 'V_2']
df = pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
                  index=pd.date_range('1/1/2020', periods=frame_rows),
                    columns=frame_columns)
df=df.cumsum()+100
df.iloc[0]=100

# plotly setup
plot_rows=1
plot_cols=2
fig = make_subplots(rows=plot_rows, cols=plot_cols)

# plotly traces
fig.add_trace(go.Scatter(x=df.index, y=df['V_1']), row=1, col=1)
#fig.add_trace(go.Scatter(x=df.index, y=df['V_2']), row=1, col=2)

# distplot
hist_data = [df['V_1'].values, df['V_2'].values]
group_labels = ['Group 1', 'Group 2']
#fig2 = ff.create_distplot(hist_data, group_labels)

# combine make_subplots, go.Scatter and ff.create_distplot(
fig.add_trace(ff.create_distplot(hist_data, group_labels), row=1, col=2)

fig.show()

这会引发相当大的 ValueError。

原因好像是go.Scatter()ff.create_distplot()return两种不同的数据类型;分别为 plotly.graph_objs.Scatterplotly.graph_objs._figure.Figure。而且 make_subplots 似乎肯定不适用于后者。或者有人知道解决这个问题的方法吗?

感谢您的任何建议!

事实证明你不能直接这样做,因为 make_subplots() 不会直接接受 plotly.graph_objs._figure.Figure 对象作为 add_trace() 的参数。但是您 可以 构建一个 ff.create_distplot' 和 "steal" 来自该图的数据并将它们应用到 go.Histogramgo.Scatter() 对象 make_subplots() 中被接受。您甚至可以对地毯/边距图做同样的事情。

剧情:

代码:

# imports
from plotly.subplots import make_subplots
import plotly.figure_factory as ff
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# data
np.random.seed(123)
frame_rows = 40
n_plots = 6
#frame_columns = ['V_'+str(e) for e in list(range(1,n_plots+1))]
frame_columns = ['V_1', 'V_2']
df = pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
                  index=pd.date_range('1/1/2020', periods=frame_rows),
                    columns=frame_columns)
df=df.cumsum()+100
df.iloc[0]=100

# plotly setup
plot_rows=2
plot_cols=2
fig = make_subplots(rows=plot_rows, cols=plot_cols)

# plotly traces
fig.add_trace(go.Scatter(x=df.index, y=df['V_1']), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['V_2']), row=2, col=1)

# distplot
hist_data = [df['V_1'].values, df['V_2'].values]
group_labels = ['Group 1', 'Group 2']
fig2 = ff.create_distplot(hist_data, group_labels)

fig.add_trace(go.Histogram(fig2['data'][0],
                           marker_color='blue'
                          ), row=1, col=2)

fig.add_trace(go.Histogram(fig2['data'][1],
                           marker_color='red'
                          ), row=1, col=2)

fig.add_trace(go.Scatter(fig2['data'][2],
                         line=dict(color='blue', width=0.5)
                        ), row=1, col=2)

fig.add_trace(go.Scatter(fig2['data'][3],
                         line=dict(color='red', width=0.5)
                        ), row=1, col=2)

# rug / margin plot to immitate ff.create_distplot
df['rug 1'] = 1.1
df['rug 2'] = 1
fig.add_trace(go.Scatter(x=df['V_1'], y = df['rug 1'],
                       mode = 'markers',
                       marker=dict(color = 'blue', symbol='line-ns-open')
                        ), row=2, col=2)

fig.add_trace(go.Scatter(x=df['V_2'], y = df['rug 2'],
                       mode = 'markers',
                       marker=dict(color = 'red', symbol='line-ns-open')
                        ), row=2, col=2)

# some manual adjustments on the rugplot
fig.update_yaxes(range=[0.95,1.15], tickfont=dict(color='rgba(0,0,0,0)', size=14), row=2, col=2)
fig.update_layout(showlegend=False)

fig.show()