如何使图例项在情节中加粗

时间:2021-06-03 03:22:48

标签: python plotly legend

我可以使用 update_xaxes 将轴标题和刻度加粗,但是有没有办法对图例中的项目执行相同的操作?

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                title="Automatic Labels Based on Data Frame Column Names")

fig.update_xaxes(tickprefix="<b>",ticksuffix ="</b><br>",title_text= "<b> sepal_length </b>" )
fig.show()

2 个答案:

答案 0 :(得分:1)

您可以使用 lambda 函数和一些基本的 html 格式:

fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>'))

并得到:

enter image description here

如果您想突出显示一个或一些图例条目,您可以在前面的语句中加上:

bold = 'versicolor'
fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>') if t.name in bold else())

并得到:

enter image description here

完整代码:

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_length", y="sepal_width", color="species",
                title="Automatic Labels Based on Data Frame Column Names")

# Plot 1
# fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>'))

# Plot 2
bold = 'versicolor'
fig.for_each_trace(lambda t: t.update(name = '<b>' + t.name +'</b>') if t.name in bold else())

fig.show()

答案 1 :(得分:0)

我不知道是否存在一种使整个图例(带有值)加粗的方法,但是您可以在 labels 方法上使用 px.scatter kwarg 设置标签,然后添加一些 html 来使很大胆。

import plotly.express as px

df = px.data.iris()
fig = px.scatter(
    df, 
    x="sepal_length", 
    y="sepal_width", 
    color="species",
    title="Automatic Labels Based on Data Frame Column Names",
    labels={
      "species": "<b>Species</b>" # here :)
    })

fig.show()
相关问题