在ploty express中将次y轴添加到条形图

2024-06-02 06:52:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

代码如下:

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()

提前谢谢


Tags: importdfdataas方式figcolorpd
1条回答
网友
1楼 · 发布于 2024-06-02 06:52:13

根据multiple axis graphs上的plotly文档:

Note: At this time, Plotly Express does not support multiple Y axes on a single figure. To make such a figure, use the make_subplots() function in conjunction with graph objects as documented below.

下面是一个使用功能更全面的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()

multi_axis_plot

如上面链接的文档页面所示,有多种方法可以实现这一点,这给了您相当大的灵活性

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

相关问题 更多 >