Adding a line to an existing plot

How can I add a horizontal line (x,y to x,y) to a plotly plot?
After it’s already been drawn?

Hello,

Stackoverflow and the Plotly docs show similar examples as far as I could see with a quick search.

Have you tried adapting those potential solutions in Anvil?

Please share what you have attempted.

self.plot_1.relayout(
  shapes=[go.layout.Shape(
    type="line",
    x0=start_dt,
    y0=-6,
    x1=end_dt,
    y1=-6,
    line=dict(
    color="LightSeaGreen",
    width=4)
  )])

But I get an error message:

Attribute Error: 'module' object has no attribute 'layout' at [TrackForm, line 979]

That’s after SUCCESSFULLY creating traces and rendering to self.plot_1 via:

 trace = go.Scatter(name = 'Latitude',
        x = x,
        y = ylat,
        hoverinfo='none',
        line = dict(
            color = grey2, 
            width = 2)
      )
      traces.append(trace)  

and

self.plot_1.data = traces    
self.plot_1.layout = dict(title = 'Track ' + str(self.trackCOMBO.selected_value),
                  xaxis = dict(title = 'time'),
                  yaxis = dict(title = 'Temperature (deg C)'))

Thank you for providing sufficient information to the question.

I don’t use Plotly, but I believe that the Plotly version 4 features, which include shapes, have not yet been incorporated into Anvil. Please see the recent post here.

In the meantime one approach would be to simply use the Scatter object to draw your line wherever you want. The Anvil Plotly documentation shows a bar chart with a scatter overlay, and so you can work from that example to try things out.

In terms of updating the chart incrementally, you could create a new object that has your Scatter chart appended to your initial data. Then, reset the whole thing to show the updated chart (e.g., self.plot_1.data=my_new_data). Perhaps more experienced Plotly users have other ways of doing this.

com-crop%20(4)

My old data gets wiped when I do that.

Clone for the above to make things a bit clearer:
https://anvil.works/build#clone:GRXVEKMFG5LTGQ2C=B2PEDX75AF5X65OLXUNDTDLE

1 Like

Thnx.
I just worked it out.
I can read the old data traces first . .

traces = self.plot_1.data
trace = go.Scatter(x = [start_dt, end_dt],
y = [-6, -6],
hoverinfo=‘none’,
line = dict(color = grey2, width = 2)
)
traces.append(trace)

2 Likes

I was writing a very long answer about update_traces in Plotly 3 and I realized the whole issue is that once the plot is rendered there isn’t a straightforward way to update it that I have heard of. The plot has to be remade. Glad you got it worked out.

2 Likes

A post was split to a new topic: Adding line to plot