首页 > 解决方案 > 摆脱覆盖的 px.bar 图上的文本标签

问题描述

我已经成功地垂直绘制了五个条形图(都具有相同的 x 轴),一个在另一个之上。每个图表分别代表不同变量(由长关键短语标识)在同一时期内的出现时间。我已将 px.bar 与 barmode = 'overlay' 和 facet_row = "Key_phrases" 一起使用。除了图例之外,该例程坚持在右侧边框上垂直书写“Key_phrases”,但短语只要它们相互重叠即可。我怎样才能关闭它并在其单独的情节中水平地写下每个短语?

标签: expressplotlylabel

解决方案


  • plotly express为多面图中的每一行迹线创建注释
  • 已经创建了一些生成长KeyPhrase的示例数据
  • 以您描述的方式生成图形
  • 演示了覆盖注释文本。另一种选择是删除注释
phrase = "The COP26 summit will bring parties together to accelerate action towards the goals of the Paris Agreement and the UN Framework Convention on Climate Change "

df = pd.DataFrame(
    {
        "Key_phrases": np.repeat(
            [" ".join(phrase.split(" ")[5 * p : 5 * (p + 1)]) for p in range(5)], 4
        ),
        "x": np.tile(range(5), 4),
        "y": np.random.uniform(1, 4, 20),
    }
)

fig = px.bar(df, x="x", y="y", facet_row="Key_phrases")
fig.show()

# override annotation text
fig.update_layout(
    annotations=[
        {**a, **{"text": f"phr.{i+1}"}}
        for i, a in enumerate(fig.to_dict()["layout"]["annotations"])
    ]
)

推荐阅读