我有 3 个带有分隔数据框和 x、y 标签的条形图。我不能使用 make_subplot 工具,因为它与 graph_object 实例兼容,而不是 express.bar。在这种情况下,我已经阅读了关于 facet_row(facet_col) 属性的文档,这些属性在一个图中绘制了条形图,但它不适合我的情况。我真的想在一页/窗口中显示 3 个不同的数字。 我创建条形图如下:
import plotly.express as px
x = ['one', 'two', 'three']
y = [1, 2, 3]
dataframe1 = {
"x_axis_1": x,
"y_axis_1": y
}
fig1 = px.bar(dataframe1, x="x_axis_1", y="y_axis_1")
fig1.update_xaxes(type='category')
提前感谢您的任何想法!
答案 0 :(得分:1)
正如您提到的,add_traces
期望我们从 plotly.graph_objects
包(例如 plotly.graph_objects.Scatter, plotly.graph_objects.Bar
)输入跟踪类的实例(参见 here)
但是,由于您不想使用 graph_objects,我们必须找到解决方法
您使用 plotly express 创建的每个 fig
都有两部分:数据和布局
例如对于您的条形图,如果我这样做:
print (fig1)
>>>
Figure({
'data': [{'alignmentgroup': 'True',
'hovertemplate': 'x_axis_1=%{x}<br>y_axis_1=%{y}<extra></extra>',
'legendgroup': '',
'marker': {'color': '#636efa'},
'name': '',
'offsetgroup': '',
'orientation': 'v',
'showlegend': False,
'textposition': 'auto',
'type': 'bar',
'x': array(['one', 'two', 'three'], dtype=object),
'xaxis': 'x',
'y': array([1, 2, 3], dtype=int64),
'yaxis': 'y'}],
'layout': {'barmode': 'relative',
'legend': {'tracegroupgap': 0},
'margin': {'t': 60},
'template': '...',
'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x_axis_1'}},
'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'y_axis_1'}}}
})
如果我们检查 data 参数,它是一个 plotly graph_object 类的列表:
print (fig1['data'][0])
>>>
Bar({
'alignmentgroup': 'True',
'hovertemplate': 'x_axis_1=%{x}<br>y_axis_1=%{y}<extra></extra>',
'legendgroup': '',
'marker': {'color': '#636efa'},
'name': '',
'offsetgroup': '',
'orientation': 'v',
'showlegend': False,
'textposition': 'auto',
'x': array(['one', 'two', 'three'], dtype=object),
'xaxis': 'x',
'y': array([1, 2, 3], dtype=int64),
'yaxis': 'y'
})
print(type(fig1['data'][0]))
>>>
<class 'plotly.graph_objs._bar.Bar'>
所以基本上我们必须从 plotly express 图形中提取它并将其传递给 add_traces
以使其工作
完整的解决方案
生成一些数据:
x1 = ['one', 'two', 'three']
y1 = [1, 2, 3]
x2 = ['five', 'six', 'seven']
y2 = [5, 6, 7]
x3 = ['eight', 'nine', 'ten']
y3 = [8, 9, 10]
dataframe1 = {
"x_axis_1": x,
"y_axis_1": y
}
dataframe2 = {
"x_axis_2": x2,
"y_axis_2": y2
}
dataframe3 = {
"x_axis_3": x3,
"y_axis_3": y3
}
生成情节:
from plotly.subplots import make_subplots
fig = make_subplots(rows=3, cols=1)
fig1 = px.bar(dataframe1, x="x_axis_1", y="y_axis_1")
fig2 = px.bar(dataframe2, x="x_axis_2", y="y_axis_2")
fig3 = px.bar(dataframe3, x="x_axis_3", y="y_axis_3")
fig.add_trace(fig1['data'][0], row=1, col=1)
fig.add_trace(fig2['data'][0], row=2, col=1)
fig.add_trace(fig3['data'][0], row=3, col=1)
fig.show()
输出:
正如您通过从 plotly express 图中查询 data
键所看到的,我们获得了需要传递给 add_traces
方法的所需格式。