簡體   English   中英

使用 Plotly Python 將 Xaxis 置於 Y 坐標 0

[英]Put the Xaxis at the Y coordinate 0 with Plotly Python

我想在情節上重現這個數字,
https://i.stack.imgur.com/bxWu8.png\\但是當我嘗試重現中心的水平線時遇到問題,如果我理解正確,只有軸可以顯示刻度線但無法選擇用於定位 X 軸的 Y 坐標。
這是到目前為止我設法重現的內容
https://i.stack.imgur.com/7xUTk.png
你有想法嗎?
提前致謝。

  • 直接用情節表達
  • 調整軌跡texttemplate="%{text:.1%}", textposition="outside", textangle=90
  • 調整布局xaxis_type="category", yaxis_tickformat=".1%", yaxis_range=[-1.4, 1.4]
    1. xaxis_type="category"所以每年都會顯示
    2. yaxis_range=[-1.4, 1.4]所以有文字的空間
import numpy as np
import pandas as pd
import plotly.express as px

df = pd.DataFrame(
    {
        "year": np.repeat(range(2011, 2021), 2),
        "cat": np.tile(list("AB"), 10),
        "val": np.random.uniform(-1, 1, 20),
    }
)

px.bar(df, x="year", y="val", color="cat", text="val", barmode="group").update_traces(
    texttemplate="%{text:.1%}", textposition="outside", textangle=90
).update_layout(
    xaxis_type="category", yaxis_tickformat=".1%", yaxis_range=[-1.4, 1.4]
).update_yaxes(
    zeroline=True, zerolinewidth=2, zerolinecolor="black"
).update_yaxes(
    showline=True, linewidth=2, linecolor="black"
)

在此處輸入圖片說明

更精致

  • 沿零軸的刻度線,圖底部的刻度標簽
  • 需要兩組跟蹤,一組用於正值,另一組用於負值
  • xaxis然后成為刻度標記的軸
  • xaxis2然后成為刻度標簽的軸
trace_opts = dict(texttemplate="%{text:.1%}", textposition="outside", textangle=90)
data_opts = dict(color="cat", text="val", barmode="group")
y_opts = {
    "tickformat": ".1%",
    "showline": True,
    "linewidth": 2,
    "linecolor": "black",
}

# positive values
figp = px.bar(
    df, x="year", y=np.where(df["val"].ge(0), df["val"], np.nan), **data_opts
).update_traces(**trace_opts)

# negative values on separate axis
fign = px.bar(
    df, x="year", y=np.where(df["val"].lt(0), df["val"], np.nan), **data_opts
).update_traces(**trace_opts, showlegend=False, yaxis="y2", xaxis="x2")

# integrate and format both sets of axis
figp.add_traces(fign.data).update_layout(
    yaxis={"domain": [0.5, 1], "range": [0, 1.5], **y_opts},
    yaxis2={"domain": [0, 0.5], "range": [-1.5, 0], **y_opts},
    xaxis=dict(
        type="category",
        ticklen=7, tickwidth=3,
        tickson="labels",
        ticks="outside",
        showticklabels=False,
    ),
    xaxis2=dict(type="category", anchor="free"),
).update_layout(xaxis_title="", xaxis2_title=figp.layout.xaxis.title)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM