简体   繁体   English

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

[英]How to hide legend with Plotly Express and Plotly

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.我试图通过首先在 Plotly Express 中创建一个简单的条形图,然后用 Plotly 对其进行更新以对其进行优化来学习 Plotly。 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基本上,我希望右边那个可怕的传说消失

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参数showlegend是您未在代码中指定的布局对象的一部分
  • The code may also work if you do not wrap the layout object my_layout inside a go.Layout() .如果您不将布局对象my_layout包装在go.Layout()该代码也可以工作。 It could work by simply keeping my_layout a dictionary它可以通过简单地将my_layout保留为字典来工作
  • as for plotly.express , try fig.update_layout(showlegend=False) .至于plotly.express ,试试fig.update_layout(showlegend=False) All the arguments are the same.所有的论点都是一样的。 Accessing them varies slightly.访问它们略有不同。

Hope it works for you.希望对你有效。

The issue with your original code is that fig.update() doesn't take fig as an argument.您原始代码的问题在于fig.update()不将fig作为参数。 That line could just be fig.update(layout_showlegend=False)那条线可能只是fig.update(layout_showlegend=False)

After creating the figure in plotly, to disable the legend you can make use of this command:在 plotly 中创建图形后,要禁用图例,您可以使用以下命令:

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.对于高级用户:您还可以通过设置每个轨迹的 showlegend 属性来启用/禁用图中单个轨迹的图例。 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/您可以在此处查看示例: https : //plotly.com/python/legend/

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

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