删除分组 plotly express 条形图中的空条,使得每组条之间的视觉距离相等

Remove empty bars in grouped plotly express bar chart, such that the visual distance between each group of bars is equal

我正在尝试对条形图的轨迹进行分组,并在每组之间保持相同的距离。

import pandas as pd
import plotly.express as px

df = pd.DataFrame({
  "City": ["Toronto", "Toronto", "Toronto", "CPH", "CPH", "London", "London"],
  "Tower name": ["T1", "T2", "T3", "T4", "T5", "T6","T7"],
  "Height": [1.0, 1.5, 2.0, 3.0, 4.0, 2.0 ,5.0],
})

fig = px.bar(x=df['City'], y=df['Height'],color = df['Tower name'], color_discrete_sequence=['black'])
fig.update_layout(showlegend=False)
fig.update_layout(barmode='group')
fig.show()

结果如下图。

我想要的解决方案是这样的

我找到了 this thread 但该线程中的解决方案建议堆叠条形图,这在我的情况下是不可能的。

您可以使用多分类轴https://plotly.com/python/categorical-axes/#multicategorical-axes

go.Figure(go.Bar(x=df.loc[:,["City", "Tower name"]].T.values, y=df["Height"].values, marker_color="black"))