将 y 轴移动到中间并在每侧制作两个图例以用于 Plotly 发散条形图

Moving y axis to the middle and making two legends on each side for Plotly diverging bar chart

我正在按照此示例代码制作发散条形图,但不知道如何:

  1. 使实体名称(A、B、C 等)位于中间(0 处)
  2. 为每一面制作两个单独的图例,而不是一个

输出图像:https://imgur.com/a/cdbc5j0

import numpy as np
import pandas as pd
import plotly.graph_objects as go

d = {'Who': ['A', 'B', 'C', 'D', 'E', 'F'],
     'Pants on Fire': [9,7,6,4, 2, 1],
     'False': [7, 6, 4, 5, 2,1],
     'Mostly False': [5, 4, 6,4, 2, 6],
     'Half True' : [4,2,5,6,3, 2],
     'Mostly True': [5,3,2,3,4,3],
    ' True': [2,4,3,6, 6, 8]}
df = pd.DataFrame(d)

fig = go.Figure()
for col in df.columns[1:4]:
    fig.add_trace(go.Bar(x=-df[col].values,
                         y=df['Who'],
                         orientation='h',
                         name=col,
                         customdata=df[col],
                         hovertemplate = "%{y}: %{customdata}"))
for col in df.columns[4:]:
    fig.add_trace(go.Bar(x= df[col],
                         y =df['Who'],
                         orientation='h',
                         name= col,
                         hovertemplate="%{y}: %{x}"))    

fig.update_layout(barmode='relative', 
                  height=400, 
                  width=700, 
                  yaxis_autorange='reversed',
                  bargap=0.01,
                  legend_orientation ='v',
                  legend_x=1.0, legend_y=1.0
                 )```
from plotly.subplots import make_subplots
import pandas as pd
import plotly.express as px

d = {
    "Who": ["A", "B", "C", "D", "E", "F"],
    "Pants on Fire": [9, 7, 6, 4, 2, 1],
    "False": [7, 6, 4, 5, 2, 1],
    "Mostly False": [5, 4, 6, 4, 2, 6],
    "Half True": [4, 2, 5, 6, 3, 2],
    "Mostly True": [5, 3, 2, 3, 4, 3],
    " True": [2, 4, 3, 6, 6, 8],
}
df = pd.DataFrame(d)

# use two sub-plots so yaxes can be in middle...
fig = make_subplots(rows=1, cols=2, horizontal_spacing=0)

# create the two figures as per question ...
fig1 = px.bar(df, y="Who", x=df.columns[1:4]).update_traces(
    legendgroup="pants", legendgrouptitle_text="Pants"
)
fig2 = px.bar(
    pd.merge(
        df["Who"],
        df.loc[:, df.select_dtypes("number").columns] * -1,
        left_index=True,
        right_index=True,
    ),
    x=df.columns[4:],
    y="Who",
).update_traces(legendgroup="truth", legendgrouptitle_text="Truth")

# add traces from figures to sub-plots figure
for t in fig1.data:
    fig.add_trace(t, row=1, col=1)
for t in fig2.data:
    fig.add_trace(t, row=1, col=2)

# final config
fig.update_layout(barmode="relative", yaxis_visible=False)
fig.update_xaxes(autorange="reversed")