Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 726
MaxS Avatar asked Oct 01 '19 11:10

MaxS


People also ask

How do you change the y axis values in Plotly?

Go to 'Axes', then 'Tick Labels' and depending on the axis you want to change, select X, Y, or 'ALL'.

How do you rotate labels in Plotly?

Tickangle=90 means that the labels will be rotated by 90° clockwise. If you use the negative sign, you rotate the labels by 90° anti-clockwise, so just the other direction.


1 Answers

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

like image 108
Albo Avatar answered Oct 18 '22 10:10

Albo