简体   繁体   中英

Plotly: How to remove the gap behind the tail of an arrow created with add_annotation()?

I am using the plotly.graph_objects.Figure.add_annotation() function to add an arrow into my plot - see a simple example code below:

import plotly.graph_objects as go

fig = go.Figure()

fig.add_annotation(ax = 3, axref = 'x', ay = 2, ayref = 'y',
                   x = 4, xref = 'x', y = 2, yref = 'y',
                   arrowhead = 3)

fig.add_shape(x0 = 1, x1 = 3, xref = 'x',
              y0 = 1, y1 = 3, yref = 'y')

fig.add_shape(x0 = 4, x1 = 6, xref = 'x',
              y0 = 1, y1 = 3, yref = 'y')

fig.update_layout(xaxis_range = [0, 7], yaxis_range = [0, 4])

fig.show()

which renders the following image:

在此处输入图像描述

As you can see, there is a small gap between the left rectangle and the tail of the arrow. Is there a way to remove this gap, so that the arrow starts exactly as specified by the parameters ax and ay ? I have tried looking through the documentation to see if there may be other relevant parameters of the add_annotation() function but couldn't find clues.

This should do it:

xanchor = 'right'

在此处输入图像描述

Complete code:

import plotly.graph_objects as go

fig = go.Figure()

fig.add_annotation(ax = 3, axref = 'x', ay = 2, ayref = 'y',
                   x = 4, xref = 'x', y = 2, yref = 'y',
                   arrowhead = 3,
                   xanchor = 'right')

fig.add_shape(x0 = 1, x1 = 3, xref = 'x',
              y0 = 1, y1 = 3, yref = 'y')

fig.add_shape(x0 = 4, x1 = 6, xref = 'x',
              y0 = 1, y1 = 3, yref = 'y')

fig.update_layout(xaxis_range = [0, 7], yaxis_range = [0, 4])

fig.show()

Explanation:

As per the documentation ,

xanchor – Sets the text box's horizontal position anchor This anchor binds the x position to the “left”, “center” or “right” of the annotation. For example, if x is set to 1, xref to “paper” and xanchor to “right” then the right-most portion of the annotation lines up with the right-most edge of the plotting area. If “auto”, the anchor is equivalent to “center” for data- referenced annotations or if there is an arrow, whereas for paper-referenced with no arrow, the anchor picked corresponds to the closest side.

Even if there is no actual annotation text, a (place-holder) text field is still rendered (anchored to the 'center' by default), which is what pushes the arrow tail. Setting the xanchor to 'right' ensures that the arrow starts where expected, while the empty text field is pushed to the left of that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM