I tried to put the font size of the first line of ticks (Tick 1, Tick 2, Tick 3) in size 15 and green and the second line of ticks in size 13 and red (description 1, description 2, description 3).
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
fig.update_layout(
yaxis=dict(title="", showgrid=True,
ticktext=[f"<b>Tick 1</b> <br> description 1", "<b>Tick 2</b> <br> description 2", "<b>Tick 3</b> <br> description 3"],
tickvals=np.arange(72,78,2),
tickfont = dict(size = 12))
)
fig.show()
Use Plotly's annotation
feature, hide the original tick labels by setting the showticklabels
attribute to False
then we can add custom annotations for each tick with the desired font sizes and colors.
edit: lets try to adjust the margin.l attribute in fig.update_layout, also we will adjust the x value for the annotation to a negative value (e.g., -0.1)
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
ticktext = ["Tick 1", "Tick 2", "Tick 3"]
desc = ["description 1", "description 2", "description 3"]
tickvals = np.arange(72, 78, 2)
fig.update_layout(
yaxis=dict(title="", showgrid=True, showticklabels=False, tickvals=tickvals),
margin=dict(l=100) # Adjust the left margin
)
for i, (tick, d, val) in enumerate(zip(ticktext, desc, tickvals)):
fig.add_annotation(
dict(
xref="paper",
yref="y",
x=-0.1, # Set x to a negative value
y=val,
text=f"<b>{tick}</b>",
showarrow=False,
font=dict(size=15, color="green"),
xanchor="left",
yanchor="middle",
)
)
fig.add_annotation(
dict(
xref="paper",
yref="y",
x=-0.1, # Set x to a negative value
y=val - 0.5,
text=d,
showarrow=False,
font=dict(size=13, color="red"),
xanchor="left",
yanchor="middle",
)
)
fig.show()