如何整理 px express 中的 x 轴标签?

How to Tidy Up x-axes label in px express?

我正在尝试整理我的 x 轴标签:

Before

对此:

After

px express 中是否有任何参数或属性可以做到这一点?

谢谢

  • 已经模拟了你的数据
  • 采用每隔一个标签显示一次的方法。然后要有所有标签,需要两个x-axes。显然如果使用两个轴,则需要两条轨迹
import numpy as np
import pandas as pd
import plotly.express as px

regions = [
    "North Sumatra",
    "West Sumatra",
    "South Sumatra",
    "West Java, Central Java",
    "Kalimantan",
    "East Java",
    "Sulawesi",
    "Maluku",
]

df = pd.DataFrame({"region": regions, "value": np.random.randint(1, 20, len(regions))})

fig = px.bar(df, x="region", y="value")
# simulate a second trace for second xaxis
fig.add_traces(
    px.bar(df, x="region", y=np.zeros(len(regions))).update_traces(xaxis="x2").data
)
# configure labels against two axis
fig.update_layout(
    xaxis={
        "tickangle": 0,
        "anchor": "free",
        "position": 0.1,
        "tickmode": "array",
        "tickvals": df["region"].tolist()[::2],
    },
    xaxis2={
        "tickangle": 0,
        "overlaying": "x",
        "anchor": "free",
        "position": 0.05,
        "tickmode": "array",
        "tickvals": df["region"].tolist()[1::2],
    },
    yaxis={"domain": [0.1, 1]},
)