📌  相关文章
📜  如何使用 Plotly Python更改图例的位置?

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

如何使用 Plotly Python更改图例的位置?

在本文中,我们将讨论如何使用Python在 Plotly 中更改图例的位置。

当一个对象的变化必须参照另一个对象来描述时,默认情况下会出现图例。图例使阅读图表更容易,因为它包含对所用颜色代码或键的描述。默认情况下,图例出现在图的右上角但在图之外,但可以根据需要定位它们。让我们首先创建一个常规图,以便可以明显看出差异。

使用的数据集:点击这里

示例:常规图

Python3
# import libraries
import plotly.express as px
import pandas as pd
  
# read dataset
data = pd.read_csv("bestsellers.csv")
  
fig = px.scatter(data, x="Year", y="Price", color="Genre")
  
fig.show()


Python3
# import the modules
import plotly.express as px
import pandas as pd
  
# read the data
data = pd.read_csv("bestsellers.csv")
  
# scatter plot
fig = px.scatter(data, x="Year", y="Price", color="Genre")
fig.update_layout(legend=dict(y=0.5))
fig.show()


Python3
# import the modules
import plotly.express as px
import pandas as pd
  
# read the dataset
data = pd.read_csv("bestsellers.csv")
  
# scatter plot
fig = px.scatter(data, x="Year", y="Price", color="Genre")
# layout
fig.update_layout(legend=dict(yanchor="top", y=0.9, xanchor="left", x=0.4))
fig.show()


输出

为了定位图例,我们使用 update_layout函数将图例设置为描述图例属性的字典。锚键设置位置,x 和 y 容纳相对于轴的边距。

语法

通过为上述参数设置适当的值,可以完成所需的任务。

示例:将图例定位到中心

Python3

# import the modules
import plotly.express as px
import pandas as pd
  
# read the data
data = pd.read_csv("bestsellers.csv")
  
# scatter plot
fig = px.scatter(data, x="Year", y="Price", color="Genre")
fig.update_layout(legend=dict(y=0.5))
fig.show()

输出

示例:在图上定位图例

Python3

# import the modules
import plotly.express as px
import pandas as pd
  
# read the dataset
data = pd.read_csv("bestsellers.csv")
  
# scatter plot
fig = px.scatter(data, x="Year", y="Price", color="Genre")
# layout
fig.update_layout(legend=dict(yanchor="top", y=0.9, xanchor="left", x=0.4))
fig.show()

输出