如何在绘图分散和不同的标记中更改文本的颜色? [英] How to change color of text in plotly scatter and different marker?

查看:59
本文介绍了如何在绘图分散和不同的标记中更改文本的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用plot.ly绘制虹膜数据集.它在散布数据工作中具有颜色参数,如seabron中的色相,但它仅更改标记的颜色,而不能更改文本的颜色,我找不到任何原因来更改每组颜色的标记类型.代码是:

I want use plot.ly to plot iris dataset. It has an color parameter in scatter data work like hue in seabron but it only change the color of marker and cant change the color of text and i cant find any why to change the marker type for each group of color. the code is :

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

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

I want the text color be like the color of each point and the 3 difrent type of marker, bc of 2 type of species.

结果是这样的,图例中有我不想要的小 Aa .

the result is like this and the legend has litel Aa that i don't want be.

推荐答案

在这里,您可以使用 for_each_trace 将文本的颜色与标记的颜色进行匹配:

Here is how you can match the color of text to the marker color, by using 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()

关于图例,使用我上面的代码在IMO中看起来已经更好了,但是没有选择可以将其关闭.您可以尝试一种方法,其中有两条轨迹,一条仅带有标记,一条带有纯文本,而一条带有纯文本,而不会出现在图例中,就像这样:

Regarding the legend, it already looks better IMO with my code above, but there is no option to turn this off. You could try an approach where you have two traces, one with just markers and one with just text and have the one with just text not appear in the legend, like so:

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

这是可行的,但可能仅使用Plotly Express函数的输出,该函数会自动设置 legendgroup ,并且对于更复杂的图形可能会有些脆弱:)

This works, but probably only using the output of Plotly Express functions, which set legendgroup automatically, and might be a bit brittle with more complex figures :)

这篇关于如何在绘图分散和不同的标记中更改文本的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆