Plotly: How to re-position ticktext close to the zero-line?

Viewed 485

Plotly seems to place the x and y ticks on the periphery of a graph by default however I have a graph which its y zero-line is in the middle. I'd like for the tick to be right beside the y axis instead but I fail to find a command to make that happen. Is it at all possible?Image of my graph in Plotly. I'd like the f(omega) to be close to the central axis

1 Answers

To my knowledge there is no direct way to do this at the moment. But if you use the correct combination of xaxis zeroline and annotations for the y-values, you can get this:

enter image description here

The code snippet below takes the max and min for the y-values, builds a list of that interval with a defined number of steps, and inserts annotations for those steps. It's not very elegant, it fails a bit when you try to zoom, but it works. At least now you don't have to try a similar approach yourself.

Complete code:

import plotly.graph_objects as go
import numpy as np

x = np.arange(-4,5)
y=x**3

yticks=list(range(y.min(), y.max(), 14))
#yticks.append(y.max())9

fig = go.Figure(data=go.Scatter(x=x, y=y))

fig.update_layout(xaxis = dict(zeroline=True,
                               zerolinecolor='firebrick',
                               title_text = "x zeroline",
                               title_standoff = 4))

fig.update_layout(yaxis = dict(zeroline=True,
                               showgrid=False,
                               title_font = {"size": 20},
                               tickfont= dict(color='rgba(0,0,0,0)')))

for i, m in enumerate(yticks):
    fig.add_annotation(dict(font=dict(color='firebrick',size=12),
                                        x=0.066,
                                        y=yticks[i],
                                        showarrow=False,
                                        text=str(yticks[i])+' -',
                                        textangle=0,
                                        xanchor='right',
                                        xref="x",
                                        yref="y"))


fig.show()
Related