简体   繁体   English

Plotly 快递怎么显示图例?

[英]Plotly Express how to show legend?

I have code below as, but I cant seem to show legend even by trying a few things manually by showing legend parameter, is there anyway to show legend?我在下面有代码,但即使通过显示图例参数手动尝试一些事情,我似乎也无法显示图例,是否有显示图例? Thanks!谢谢!

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

When px.line is prompted to produce figure with a single line, the default behavior is to drop the legend.当提示px.line生成单行图形时,默认行为是删除图例。 This is presumably intended to reduce redundant informatin since it's easy to include the data description in the main title and/or the axis title.这可能是为了减少冗余信息,因为很容易在主标题和/或轴标题中包含数据描述。 In order to override this, just include:为了覆盖它,只需包括:

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

In your case, you'll have to do so for both your initial figures before they are joined in subfig .在您的情况下,您必须在将两个初始数字加入subfig之前都这样做。 Here's and exampe with the gapminder dataset:以下是gapminder数据集的示例:

Plot: Plot:

在此处输入图像描述

Complete code:完整代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM