如何更改 plotly scatter 和不同标记中文本的颜色?

Tav*_*oli 2 python colors legend plotly

我想使用 plot.ly 来绘制虹膜数据集。它在分散数据中有一个颜色参数,就像 seabron 中的色调一样,但它只改变标记的颜色而不能改变文本的颜色,我找不到任何改变每组颜色的标记类型的原因。代码是:

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",  text='sepal_width')
fig.update_traces(textposition='top center', textfont_size=14, textfont_color=c)
fig.show()
Run Code Online (Sandbox Code Playgroud)

我希望文本颜色像每个点的颜色和 3 种不同类型的标记,2 种类型的 bc。

结果是这样的,传说中有Aa我不想要的东西。 在此处输入图片说明

nic*_*ten 5

以下是使用以下方法将文本颜色与标记颜色匹配的方法for_each_trace

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",  text='sepal_width')
fig.for_each_trace(lambda t: t.update(textfont_color=t.marker.color, textposition='top center'))
fig.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

关于图例,我上面的代码在 IMO 看起来已经更好了,但是没有选项可以关闭它。您可以尝试一种方法,其中有两条轨迹,一条只有标记,一条只有文本,只有文本没有出现在图例中,如下所示:

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", text='sepal_width')
def add_trace_copy(trace):
    fig.add_traces(trace)
    new_trace = fig.data[-1]
    new_trace.update(textfont_color=trace.marker.color, textposition='top center', 
                     mode="text", showlegend=False)
    trace.update(mode="markers")
fig.for_each_trace(add_trace_copy)
fig.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

这是有效的,但可能仅使用legendgroup自动设置的 Plotly Express 函数的输出,并且对于更复杂的数字可能有点脆弱:)