我有下面的代码作为,但我似乎不能显示图例,即使通过手动try 一些事情显示图例参数,有没有显示图例?谢谢!

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

# create two independent figures with px.line each containing data from multiple columns
fig = px.line(dfa, y="revenue", template=template_style,markers=True)
fig2 = px.line(dfa, y="pdt_chg", template=template_style,markers=True)

fig2.update_traces(yaxis="y2")

subfig.add_traces(fig.data + fig2.data)
subfig.layout.title="Sales"
subfig.layout.xaxis.title="Year"
subfig.layout.yaxis.title="$"
subfig.layout.yaxis2.title="%"
subfig.update_layout(
    xaxis = dict(
        tickmode = 'linear',
        tick0 = 0,
        dtick = 0),title_x= 0.47,template=template_style)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))
subfig.show()

推荐答案

当提示px.line生成单线图形时,默认行为是丢弃图例.这大概是为了减少冗余信息,因为很容易在主标题和/或轴标题中包含数据描述.要覆盖此设置,只需包括:

fig.for_each_trace(lambda t: t.update(name = <a name>))
fig.update_traces(showlegend = True)

在你的情况下,你必须对你的两个初始数字都这样做,然后才能将它们合并到subfig.以下是gapminder数据集的示例:

剧情:

enter image description here

完整代码:

import plotly.express as px
from plotly.subplots import make_subplots

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

df1 = px.data.gapminder().query("country=='Canada'")
fig1 = px.line(df1, x="year", y="lifeExp", title='Life expectancy in Canada')
fig1.for_each_trace(lambda t: t.update(name = 'Canada'))
fig1.update_traces(showlegend = True)


df2 = px.data.gapminder().query("country=='Germany'")
fig2 = px.line(df2, x="year", y="lifeExp", title='Life expectancy in Germany')
fig2.for_each_trace(lambda t: t.update(name = 'Germany'))
fig2.update_traces(showlegend = True)


subfig.add_traces(fig1.data + fig2.data)
subfig.for_each_trace(lambda t: t.update(line=dict(color=t.marker.color)))

subfig.show()

Python相关问答推荐

如何以实现以下所述的预期行为的方式添加两只Pandas pyramme

如果我已经使用了time,如何要求Python在12秒后执行另一个操作.sleep

在Arrow上迭代的快速方法.Julia中包含3000万行和25列的表

Python会扔掉未使用的表情吗?

根据条件将新值添加到下面的行或下面新创建的行中

滚动和,句号来自Pandas列

如何使用Python将工作表从一个Excel工作簿复制粘贴到另一个工作簿?

如何使用html从excel中提取条件格式规则列表?

如何制作10,000年及以后的日期时间对象?

有没有一种方法可以从python的pussompy比较结果中提取文本?

如何在WSL2中更新Python到最新版本(3.12.2)?

如果满足某些条件,则用另一个数据帧列中的值填充空数据帧或数组

如何根据一列的值有条件地 Select 前N组?

改进大型数据集的框架性能

CommandeError:模块numba没有属性generated_jit''''

从Windows Python脚本在WSL上运行Linux应用程序

在极中解析带有数字和SI前缀的字符串

如何使用两个关键函数来排序一个多索引框架?

Discord.py -

Pandas—堆栈多索引头,但不包括第一列