【问题标题】:Adding secondary y axis to bar line chart in ploty express在 plotly express 中将次 y 轴添加到条形折线图
【发布时间】:2021-05-05 19:01:40
【问题描述】:

我有一个简单的条形折线图。如何添加辅助 y 轴,以便以更具代表性的方式显示折线图 (Column1)。

这是代码:

import pandas as pd
import dash
import plotly.express as px

data = [['A',100,880],['B ',50,450],['C',25,1200]]
df = pd.DataFrame(data,columns=['Letter','Column1','Column2'])
fig = px.line(x=df['Letter'], y=df['Column1'], color=px.Constant("Column1"),
             labels=dict(x="Letter", y="Column2", color="Legend"))
fig.add_bar(x=df['Letter'], y=df['Column2'], name="Letter")
fig.show()

提前致谢!

【问题讨论】:

标签: python plotly


【解决方案1】:

根据multiple axis graphs 上的情节文档:

注意:此时,Plotly Express 不支持单个图形上的多个 Y 轴。要制作这样的图形,请结合使用 make_subplots() 函数和图形对象,如下所述。

这是一个使用功能更全的graph_objects的解决方案:

import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

data = [['A',100,880],['B ',50,450],['C',25,1200]]
df = pd.DataFrame(data,columns=['Letter','Column1','Column2'])

fig = make_subplots(specs=[[{"secondary_y": True}]])

fig.add_trace(
    go.Scatter(x=df['Letter'], y=df['Column1'], name="Column1", mode="lines"),
    secondary_y=True
)

fig.add_trace(
    go.Bar(x=df['Letter'], y=df['Column2'], name="Letter"),
    secondary_y=False
)

fig.update_xaxes(title_text="Letter")

# Set y-axes titles
fig.update_yaxes(title_text="Column2", secondary_y=False)
fig.update_yaxes(title_text="Column1", secondary_y=True)

fig.show()

给了

如上面链接的文档页面所示,有多种方法可以实现这一点,从而为您提供相当多的灵活性。

虽然没有得到官方支持,但如果你觉得自己真的需要express,你可以试试this SO post提供的答案。

【讨论】:

    猜你喜欢
    • 2019-08-08
    • 2021-01-12
    • 2015-03-20
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多