python - 使用 Plotly Python 将 X 轴置于 Y 坐标 0

标签 python plotly

我想在plotly上重现这个图,
/image/bxWu8.png\ 但是当我尝试重现中心的水平线时遇到问题,如果我理解正确的话,只有轴可以显示刻度线,但不可能选择 Y 坐标来定位 X 轴。
这是到目前为止我已经成功重现的内容
/image/7xUTk.png
你有什么想法吗?
提前致谢。

最佳答案

  • 直接用 plotly 表达
  • 调整轨迹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"
)

enter image description here

更复杂

  • 沿零轴的刻度线,图底部的刻度标签
  • 需要两组迹线,一组用于正值,另一组用于负值
  • 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)

enter image description here

关于python - 使用 Plotly Python 将 X 轴置于 Y 坐标 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69573079/

相关文章:

r - 超过100个类别的散布堆积条形图

python - Selenium Webdriver (ChromeDriver) - 给出未知错误 : Runtime.executionContextCreated 具有无效的“上下文错误”

python - choropleth Plotly map 中的自定义垃圾箱

r - 包装长轴标签

python - 使用 Python Pandas 从 Google Drive 或任何云服务读取 CSV 文件

python - 自定义悬停框 Plotly : Python to Fit Text

R Plotly 无法从条形图中删除跟踪 0

python - 在 Django 中测试时的模型创建顺序?

python - 使用 pd.read_fwf 读取固定宽度文件时出现 ValueError - 预期字段数与看到的数字不匹配

python - 使用 POX 创建 TCP 数据包