Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

python - How to color ticktext in plotly?

I would like to display my ticktexts in my plotly xaxis with different colors based on the respective string (based on a dictionary). Is there a functionality in plotly to do this, maybe via HTML coding?

 ticktext = ['<font color="red">{}</font> '.format(x) for x in ticktexts]

doesn't work, it gives the html string to the labels.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A little bit of a workaround using LaTeX can help you here (sorry @Iwileczek, I stole your example, hope you don't mind) because plotly has full LaTeX support:

def color(color, text):
    s = '$color{' + str(color) + '}{' + str(text) + '}$'
    return s

animals=['giraffes', 'orangutans', 'monkeys']

colors = ['red', 'green', 'yellow', 'blue']
ticks = [5, 10, 15, 20]
keys = dict(zip(ticks, colors))

fig = go.Figure([go.Bar(x=animals, y=[20, 14, 23])])
ticktext = [color(v, k) for k, v in keys.items()]
print(ticktext)
fig.update_layout(
yaxis=dict(tickmode='array', ticktext=ticktext, tickvals=ticks)
)
fig.show()

enter image description here


Update March 2021:

If you don't want to use the LaTex rendered font by MathJax in your output, use the solution of @Dapcer with an HTML styling:

def color(color, text):
    return f"<span style='color:{str(color)}'> {str(text)} </span>"

Example with fig.update_layout(font=dict(family="Times New Roman") [...]: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...