【问题标题】:How to hide legend with Plotly Express and Plotly如何使用 Plotly Express 和 Plotly 隐藏图例
【发布时间】:2019-11-04 20:08:06
【问题描述】:

我正在尝试学习 Plotly,首先在 Plotly Express 中创建一个简单的条形图,然后使用 Plotly 对其进行更新以对其进行优化。我想隐藏图例。

我试图通过隐藏图例来更新原始图形,但我无法让它工作。 This is my traceback error.

还有我的代码

import plotly.plotly as py
import plotly.graph_objs as go
import plotly_express as px
import pandas as pd


df = pd.read_csv('C:/Users/Documents/Python/CKANMay.csv')

fig = px.bar(df, x="Publisher", y="Views", color="Publisher", barmode="overlay")

fig.update(fig, showlegend="false")

This is what the chart looks like now with the legend。基本上,我希望右边那个可怕的传说消失

【问题讨论】:

    标签: python plotly data-visualization plotly-python


    【解决方案1】:

    试试这个:

    my_data = [go.Bar( x = df.Publisher, y = df.Views)]
    my_layout = go.Layout({"title": "Views by publisher",
                           "yaxis": {"title":"Views"},
                           "xaxis": {"title":"Publisher"},
                           "showlegend": False})
    
    fig = go.Figure(data = my_data, layout = my_layout)
    
    py.iplot(fig)
    
    • 参数showlegend 是您未在代码中指定的布局对象的一部分
    • 如果您不将布局对象my_layout 包装在go.Layout() 中,该代码也可能有效。只需将 my_layout 保存为字典即可
    • 至于plotly.express,试试fig.update_layout(showlegend=False)。所有的论点都是一样的。访问它们略有不同。

    希望它对你有用。

    【讨论】:

    • 完美运行。谢谢!
    • 这并不能完全回答这个问题 - 如何在 Plotly Express 中隐藏图例?
    【解决方案2】:

    您的原始代码的问题是 fig.update() 没有将 fig 作为参数。该行可能只是fig.update(layout_showlegend=False)

    【讨论】:

    【解决方案3】:

    在 plotly 中创建图形后,要禁用图例,您可以使用以下命令:

    fig.update_layout(showlegend=False)
    

    对于高级用户: 您还可以通过设置每条迹线的 showlegend 属性来启用/禁用图中各个迹线的图例。例如:

    fig.add_trace(go.Scatter(
        x=[1, 2],
        y=[1, 2],
        showlegend=False))
    

    您可以在此处查看示例:https://plotly.com/python/legend/

    【讨论】:

      猜你喜欢
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2020-11-01
      • 2021-10-27
      • 2021-07-21
      • 1970-01-01
      • 2021-09-23
      相关资源
      最近更新 更多