在 Plotly 中,我们可以通过改变顺序、调整方向、隐藏或显示图例来对其进行自定义,还可以进行增大尺寸、更改字体和颜色等修改。在本文中,让我们看看自定义图例的不同方法。
为了自定义图例,我们使用 update_layout() 方法。
> 语法: update_layout(dict1=None, overwrite=False, **kwargs)
>
>
> 输入字典 / 关键字参数中的值用于迭代地更改原始布局的各个部分。
>
>
> 参数:
>
>
> – dict1 (dict) – 待更新的属性字典。
> – overwrite (bool) – 如果为 True,现有属性将被覆盖。如果为 False,则递归地将更新应用于现有属性,并保留更新操作中未指定的属性。
> – kwargs – 待更新的属性关键字/值对。
示例 1:显示和隐藏图例
隐藏图例:在下面的代码中,我们导入了 INLINECODE8fd43884 包和 INLINECODE4c7a2494 包。导入 CSV 文件后,显示一个散点图,然后通过 INLINECODE08f5043f 方法进一步修改该图,并将参数 INLINECODE3035524e 设置为 False。
要获取 CSV 文件,请点击 iris
#import packages
import plotly.express as px
import pandas as pd
# importing csv file
df = pd.read_csv("iris.csv")
# scatter plot using plotly
fig = px.scatter(df, x="sepal_length",
y="sepal_width",
color="species")
# initializing showlegend to "False"
fig.update_layout(showlegend=False)
fig.show()
输出: 图例未显示。
默认情况下,showlegend 参数为 True。当我们在 Plotly 中绘制图表时,图例始终会显示。
# import packages
import plotly.express as px
import pandas as pd
# importing csv file
df = pd.read_csv("iris.csv")
# scatter plot using plotly
fig = px.scatter(df, x="sepal_length",
y="sepal_width",
color="species")
fig.show()
输出:
示例 2:更改图例顺序
在下面的代码中,我们引入了一个新参数 legend_traceorder,并将其初始化为 "reversed"。这样做之后,图例的顺序就反转了。
# import packages
import plotly.express as px
import pandas as pd
# importing csv file
df = pd.read_csv("iris.csv")
# scatter plot using plotly
fig = px.scatter(df, x="sepal_length",
y="sepal_width",
color="species")
# order of legend is reversed
fig.update_layout(legend_traceorder="reversed")
fig.show()
输出:
更改顺序前:
更改顺序后:
顺序 setosa, versicolor, verginica 变为了 virginica, versicolour, setosa。
示例 3:更改图例方向
对于水平图例,将 layout.legend.orientation 属性设置为 "h"。在这里我们还将其放置在绘图区域的上方。通常,图例是垂直显示的。
# import packages
import plotly.express as px
import pandas as pd
# importing csv file
df = pd.read_csv("iris.csv")
# scatter plot using plotly
fig = px.scatter(df, x="sepal_length",
y="sepal_width",
color="species")
# changing orientation of the legend
fig.update_layout(legend=dict(
orientation="h",
))
fig.show()
输出:
示例 4:更改图例的大小、字体和颜色
在这个示例中,我们引入了许多其他参数,例如 INLINECODEec48f87e、INLINECODE31bb4bb3(其中指定了用于样式的子参数字典)、bgcolor(背景颜色)、边框颜色和边框宽度。
# import packages
import plotly.express as px
import pandas as pd
# importing csv file
df = pd.read_csv("iris.csv")
# scatter plot using plotly
fig = px.scatter(df, x="sepal_length",
y="sepal_width",
color="species")
# adding different style parameters to the legend
fig.update_layout(
legend=dict(
x=0,
y=1,
title_font_family="Times New Roman",
font=dict(
family="Courier",
size=12,
color="black"
),
bgcolor="LightBlue",
bordercolor="Black",
borderwidth=1
)
)
fig.show()
输出:
![image