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

ves*_*and 6 python plotly plotly-python

使用 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()
Run Code Online (Sandbox Code Playgroud)

go.Scatter()用相似的对象替换对象很容易:

阴谋:

在此处输入图片说明

但我似乎无法找到一种方法来将此设置与ff.create_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()
Run Code Online (Sandbox Code Playgroud)

这会引发相当大的 ValueError。

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

感谢您的任何建议!

ves*_*and 6

事实证明,您不能直接执行此操作,因为make_subplots()不会直接接受plotly.graph_objs._figure.Figure对象作为参数add_trace()。但是您可以构建一个ff.create_distplot' 并从该图中“窃取”数据,并将它们应用于go.Histogram和中接受的go.Scatter()对象的组合中。您甚至可以对 rug / margin plot 做同样的事情。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()
Run Code Online (Sandbox Code Playgroud)

  • 这是一个措辞非常好的问题,并且有一个示例性的、说明性的解决方案。干得好@vestland。谢谢你,这也对我有帮助! (2认同)