How to add a single tick value to default ticks on an axis?

Hi!

I’d like to combine two things: a single tick value, and the default ticks on a y axis.

image

I can do either or, by writing figure.update_yaxes(tickvals=[average], ticktext['Average: ’ + str(average)]) and then I get the lefthand case above, or not doing it and then I get the righthand case.

Can you append to default ticks? Or maybe the default tick function can be re-used, modified and applied explicitly if one knows it?

Bro did you find any solution for this?. I am stuck at the same thing but found a workaround. You can just add a hline and annotate it

fig.add_hline(y=tick_value,opacity=0.3,line=dict(dash="dash")
fig.add_annotation(x=0,y=tick_value,text=f"Average {tick_value} km",xref="x",yref="paper",yanchor="top") 
#If you want the text to appear on the other end of the line make x=1

If anyone knows a better solution please do reply!

Hi @H4CK3R !

Welcome on the forum! :tada:

Your solution seems good to me! :+1:

You can also use annotation as parameter in add_hline(), which can be more convenient to position the annotation, relative to the hline.
Try different positions using combinations of: (None|'top'|'bottom') + (None|'left'|'right')

Here is an example:

import plotly.express as px

df = px.data.iris()
fig = px.scatter(df, x="petal_length", y="petal_width")

mean = df["petal_width"].mean()

fig.add_hline(y=mean, line_dash="dot",
              annotation_text=f"Mean<br>{mean:.2f}",
              annotation_position="left")

fig.update_yaxes(showticklabels=False)
fig.show()

The function add_hline() will create and position the annotation for you, then, you can use any annotation parameters with fig.update_annotations().

If you need more fine grained positioning you can use xshift / yshift.

Here an example adding an arrow and a border by adding

fig.update_annotations(
    showarrow=True, arrowhead=2,
    bordercolor="black", borderpad=5,
)

Here is the annotation reference for all parameters:

2 Likes

I didn’t know that you could add it right in the hline itself. Thank you for the concise solution.