如何使用 Plotly Express 和 Plotly 隐藏图例

kra*_*jza 13 python data-visualization plotly plotly-python

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

我试图通过隐藏图例来更新原始图形,但我无法让它工作。这是我的回溯错误

还有我的代码

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")
Run Code Online (Sandbox Code Playgroud)

这就是图表现在带有图例的样子。基本上,我希望右边那个可怕的传说消失

hus*_*sam 8

try this:

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)
Run Code Online (Sandbox Code Playgroud)
  • the argument showlegend is part of layout object which you did not specify in your code
  • The code may also work if you do not wrap the layout object my_layout inside a go.Layout(). It could work by simply keeping my_layout a dictionary
  • as for plotly.express, try fig.update_layout(showlegend=False). All the arguments are the same. Accessing them varies slightly.

Hope it works for you.

  • 这并不能完全回答这个问题——如何在 Plotly Express 中隐藏图例? (2认同)

nic*_*ten 6

您原始代码的问题在于fig.update()它不fig作为参数。那条线可能只是fig.update(layout_showlegend=False)


Nit*_*ish 5

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

fig.update_layout(showlegend=False)
Run Code Online (Sandbox Code Playgroud)

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

fig.add_trace(go.Scatter(
    x=[1, 2],
    y=[1, 2],
    showlegend=False))
Run Code Online (Sandbox Code Playgroud)

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