📜  如何在Python中使用 Plotly Express 和 Plotly 隐藏图例?

📅  最后修改于: 2022-05-13 01:54:55.560000             🧑  作者: Mango

如何在Python中使用 Plotly Express 和 Plotly 隐藏图例?

在本文中,我们将学习如何使用 Plotly Express 和 Plotly 隐藏图例。在这里,我们将讨论在 plotly 和 plotly express 中隐藏图例的两种不同方法,每种方法使用两个不同的示例以使其更加清晰。

示例 1:

在这个例子中,我们在fig.update_traces(showlegend=False)方法的帮助下在Plotly Express中隐藏了图例,绕过了 show legend 参数为 False。

Python3
# importing packages
import plotly.express as px
  
# using the gapminder dataset
df = px.data.tips()
fig = px.scatter(df, x="total_bill", y="tip", color="sex", 
                 symbol="smoker", facet_col="time",
                 labels={"sex": "Gender", "smoker": "Smokes"})
  
# hiding legend in pyplot express.
fig.update_traces(showlegend=False)
  
fig.show()


Python3
import plotly.graph_objects as go
  
# using the Figure dataset
fig = go.Figure()
  
fig.add_trace(go.Line(name="first", x=["a", "b"], y=[1,3]))
fig.add_trace(go.Line(name="second", x=["a", "b"], y=[2,1]))
fig.add_trace(go.Line(name="third", x=["a", "b"], y=[1,2]))
fig.add_trace(go.Line(name="fourth", x=["a", "b"], y=[2,3]))
  
  
# hiding legend in pyplot express.
fig.update(layout_showlegend=False)
  
fig.show()


Python3
import plotly.express as px
  
# using the iris dataset
df = px.data.iris()
  
# plotting the line chart
fig = px.line(df, y="sepal_width", line_dash='species',
            color='species')
  
# hiding legend in pyplot express.
fig.update_traces(showlegend=False)
  
# showing the plot
fig.show()


输出:

示例 2:

在此示例中,我们借助方法fig.update(layout_showlegend=False)将 showlegend 参数传递为 False,在Plotly中隐藏图例。

Python3

import plotly.graph_objects as go
  
# using the Figure dataset
fig = go.Figure()
  
fig.add_trace(go.Line(name="first", x=["a", "b"], y=[1,3]))
fig.add_trace(go.Line(name="second", x=["a", "b"], y=[2,1]))
fig.add_trace(go.Line(name="third", x=["a", "b"], y=[1,2]))
fig.add_trace(go.Line(name="fourth", x=["a", "b"], y=[2,3]))
  
  
# hiding legend in pyplot express.
fig.update(layout_showlegend=False)
  
fig.show()

输出:

示例 3:

在此示例中,我们借助方法fig.update_traces(showlegend=False)将 layout_showlegend 参数传递为 False,在Plotly Express中隐藏图例。

Python3

import plotly.express as px
  
# using the iris dataset
df = px.data.iris()
  
# plotting the line chart
fig = px.line(df, y="sepal_width", line_dash='species',
            color='species')
  
# hiding legend in pyplot express.
fig.update_traces(showlegend=False)
  
# showing the plot
fig.show()

输出: