如何在 Plotly 散点图中改变文本颜色和不同标记的颜色?

6

我想使用plot.ly绘制鸢尾花数据集。在散点图数据中,它有一个颜色参数,类似于seabron中的hue,但它只能改变标记的颜色,不能改变文本的颜色,也找不到任何方法来为每个颜色组更改标记类型。代码如下:

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()

我希望文本颜色能像每个点和三种不同类型的标记的颜色一样,因为有两种不同的物种。

结果应该像这样,图例上有一个我不想要的小 Aaenter image description here

1个回答

12
更新:在Plotly.py的v5版本中已经移除了Aa,所以下面回答中的这部分内容适用于v4及以下版本。
以下是如何使用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()

enter image description here

关于图例,我认为使用上述代码后已经看起来更好了,但是没有关闭此选项的选项。您可以尝试一种方法,其中您有两个跟踪,一个只有标记,另一个只有文本,并且只有一个带有文本而不出现在图例中,例如:

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()

enter image description here

这个方法有效,但可能只适用于使用Plotly Express函数输出的图形,因为它们自动设置了legendgroup,在更复杂的图形中可能会有些脆弱 :)


优秀的回答。注意:在第一个代码块中,图例文本对我来说不存在,因此Plotly可能已经删除了这种行为。 - scottlittle
1
是的,在 Plotly.py v5(以及底层的 Plotly.js v2)中,我们删除了这个小的 Aa,因为存在诸如此类的担忧 :) - nicolaskruchten

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接