57

I am trying to learn Plotly by firstly creating a simple bar chart in Plotly Express and then updating it with Plotly to finesse it. I would like to hide the legend.

I am trying to update the original figure by hiding the legend, and I can't get it to work. This is my traceback error.

And my code

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. Basically, I want that awful legend on the right to go away

3 Answers 3

80

After creating the figure in plotly, to disable the legend you can make use of this command:

fig.update_layout(showlegend=False)

For Advanced users: You can also enable/disable the legend for individual traces in a figure by setting the showlegend property of each trace. For instance:

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

You can view the examples here: https://plotly.com/python/legend/

Sign up to request clarification or add additional context in comments.

Comments

19

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)
  • 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.

2 Comments

Works perfectly. Thanks!
This does not answer the question entirely - how does one hide the legend in Plotly Express?
13

The issue with your original code is that fig.update() doesn't take fig as an argument. That line could just be fig.update(layout_showlegend=False)

1 Comment

can also customize via fig.update_layout(legend={"xanchor":"center", "yanchor":"top"}) Docs: plot.ly/python/reference/#layout-legend

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.