如何使用plotly.express 在plotly 中添加辅助xaxis?

问题描述

我只找到了 yaxis 的例子。按照它之后,我得到了一个错误

Invalid key specified in an element of the 'specs' argument to make_subplots: 'secondary_x'
    Valid keys include: ['type','secondary_y','colspan','rowspan','l','r','b','t']

我的代码如下:

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

from plotly.subplots import make_subplots

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df2=pd.DataFrame({'x':[1,'y':[7,8,9]})

fig = px.scatter(df1,x='A',y='B')
fig.add_scatter(x=df2['x'],y=df2['y'])

fig.update_traces(name='Points',showlegend = True)


# Fake figure due to axis
subfig = make_subplots(specs=[[{"secondary_x": True}]])
df2=pd.DataFrame({'C':[10,20,30],'D':[40,50,60]})
fig2 = px.scatter(df2,x='C',y='D')
fig2.update_traces(xaxis="x2")
subfig.add_traces(fig.data + fig2.data)

fig.show()

咨询后

代码包含:

fig.update_layout(legend=dict(
    yanchor="top",y=0.99,xanchor="left",x=0.83,font=dict(
        family="Trebuchet",size=20,color="black"
     ),bgcolor="LightGray",bordercolor="Black",borderwidth=0
))

是否可以将这个和 fig.layout = layout 结合起来?

解决方法

Plotly 中的 make_subplots 方法不支持辅助 x 轴。但是,您可以使用 layoutXAxis 方法在 YAxis 中自行创建辅助 x 轴,您可以使用以下方法导入:from plotly.graph_objs.layout import YAxis,XAxis

然后您将 fig.layout 设置为您创建的布局,当您想使用辅助 x 轴和辅助 y 轴时,将它们作为参数传递给 go.Scatter

就您而言,我认为自己创建辅助 y 轴和辅助 x 轴看起来更简洁,而且这也无需使用 make_subplots 方法。

更新:您可以向布局添加其他参数以设置图例格式。

import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from plotly.graph_objs.layout import YAxis,XAxis

## sample DataFrames
df1=pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
df2=pd.DataFrame({'x':[1,'y':[7,8,9]})

## sample DataFrame with different x-axis and y-axis
df3=pd.DataFrame({'C':[10,20,30],'D':[40,50,60]})

## add a secondary xaxis and yaxis in the layout
layout = go.Layout(
    xaxis2 = XAxis( 
        overlaying='x',side='top',),yaxis2=YAxis(
        overlaying='y',side='right',legend=dict(
        yanchor="top",y=0.99,xanchor="left",x=0.83,font=dict(
            family="Trebuchet",size=20,color="black"
         ),bgcolor="LightGray",bordercolor="Black",borderwidth=0
    )
)

fig = px.scatter(df1,x='A',y='B')
fig.add_scatter(x=df2['x'],y=df2['y'])
fig.update_traces(name='Points',showlegend = True)

## set the layout to be the figure layout
fig.layout = layout

## add the final trace specifying the secondary x-axis and secondary y-axis
fig.add_trace(go.Scatter(x=df3['C'],y=df3['D'],xaxis='x2',yaxis='y2'))

fig.show()

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...