How to color ticktext in plotly?

只愿长相守 提交于 2021-02-04 19:15:26

问题


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.


回答1:


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




回答2:


Please see Albo's answer!


You can change to a single color by updating the color property of the yaxis or xaxis. The color property must be a single color as it only accepts strings that decode to colors. However, you can update the ticktext property of charts with Latex formatting to accomplish this. Please see Albo's answer to learn how to do this.

    import plotly.graph_objects as go
    animals=['giraffes', 'orangutans', 'monkeys']

    fig = go.Figure([go.Bar(x=animals, y=[20, 14, 23])])
    fig.update_layout(
    yaxis=dict(color="#E90")

    )
    fig.show()

Documentation

  • y-axis color
  • tick text
  • Plotly & LaTex (slightly out of date)



回答3:


HTML alternative to Albo's solution:

I used Albo's solution and replaced Latex code with HTML code. Same solution but avoiding Latex fonts if you are not inserting Math symbols.

Just replace Latex code from

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

to HTML code

def color(color, text):
    # color: hexadecimal
    s = "<span style='color:" + str(color) + "'>" + str(text) + "</span>$"
    return s


来源:https://stackoverflow.com/questions/58183962/how-to-color-ticktext-in-plotly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!