0

I would like to create a candle simulator where the next value is plotted after an event (mouse click or timer).

Instead of showing the whole plot, unshadow the next value on demand (aka append a new value).

  1. The interactive plotly graph allows to interact with different plots.

  2. Interactive mouse click gives the coordinates of the mouse position. this is not the desired result

I tried to update the graph adding next value and plot.show() again, which creates a new graph (windows).

This should work with any graph, but giving an ohlc with ema indicator as an example:

import plotly.graph_objects as go
import pandas as pd
import plotly.express as px

df2 =df(0) 
fig = go.Figure()  
fig.add_trace(go.Ohlc(x=df2.index, open=df2['Open'], high=df2['High'], low=df2['Low'], close=df2['Close'],name='plot1'))
fig.add_trace(go.Scatter(x=df2.index, y=df2['ema13'],opacity=0.7, line=dict(color='blue', width=2),name='plot2'))
fig.update_layout(xaxis_rangeslider_visible=False)
fig.show()
for i in len(df):
    input("Press enter to continue")
    df2.append(df(i))
    fig.update_traces(x=df2.index, open=df2['Open'], high=df2['High'], low=df2['Low'], close=df2['Close'],name='plot1')
    fig.update_traces(x=df2.index, y=df2['ema13'],opacity=0.7, line=dict(color='blue', width=2),name='plot2')
    fig.show()'
Almodius
  • 3
  • 3

1 Answers1

0

You mention that you tried updating the graph. To improve the question, please share a minimal reproducible example (including dummy data), so we can evaluate how much additional info you need.

The solution lies in defining an update event and change fig.data. Connect this function to either an onclick on Python, or a timer. This code starts with the first datapoint. Then you need to click on the graph (any datapoint) to add the next.

import plotly.graph_objects as go
import pandas as pd

fig = go.FigureWidget()

ix_max = 1

df = pd.DataFrame({'x':[1, 2, 3], 'y':[10, 11, 12]})

fig.add_trace(go.Scatter(x=df['x'][:ix_max],
                         y=df['y'][:ix_max],
                         name='trace1'))

def update_graph(trace, points, state):

    global ix_max

    ix_max += 1

    with fig.batch_update():

        fig.update_traces(
            x=df['x'][:ix_max],
            y=df['y'][:ix_max],
            selector=dict(name='trace1'))  # this changes x and y of the trace named here. Otherwise all traces are affected

# This next part makes sure it works regardless of which trace is on top
for i in range(len(fig.data)):
    f = fig.data[i]
    f.on_click(update_graph)

fig
StephanT
  • 649
  • 5
  • 12
  • Thank you for your answer. Your approach is similar to mine but yours seems more correct at first glance. unfortunately not sure I am getting the expected results. does your code plot the graph? when adding the fig.show (to show in a browser) it doesn't loop Edited my initial question with my full code. In my case the problem is that a new plot is open everytime – Almodius Jul 04 '23 at 11:54
  • Your method is a bit ... brute-forced ;-) My code displays the graph by calling fig. I'm running in VS Code, and I don't output to the browser. The fig.show() indeed creates a new graph each time, which is correct behavior for the command, especially inside the loop. I do notice that I cannot get it working in the browser either. I will look a bit more into it, but I think it has to do with the browser being a full HTML "render" without the supporting Python code. So it loses the connection. – StephanT Jul 04 '23 at 13:02
  • https://community.plotly.com/t/cannot-get-on-click-to-work-with-plotly-and-go-scatter/28953/2 – StephanT Jul 04 '23 at 13:14
  • "brute forced" sounds elegant, I saw it answering the question although knowing it is not correct. I am using browser as default but any other way of presenting the plot will do. Also using VS code but when executing it plots the graph in the browser – Almodius Jul 04 '23 at 13:47
  • you can force the output renderer by fig.show(renderer="vscode") Also see https://stackoverflow.com/questions/64849484/display-plotly-plot-inside-vs-code – StephanT Jul 04 '23 at 13:55
  • From what you mention, you are running it in "interactive window", I had to change presentation from "text/plain" to "vnd.jupyter.widget" Now it works but I need to click on a dot point, would it be possible to: 1-plot in a new full windows 2-plot next value without pointing a value (just mouse or keyboard click) – Almodius Jul 04 '23 at 15:05
  • I don't know how to get it to work in a separate window. Some people point to Dash to do so (which is basically Plotly on steroids) https://stackoverflow.com/questions/63716543/plotly-how-to-update-redraw-a-plotly-express-figure-with-new-data. – StephanT Jul 05 '23 at 07:31
  • An alternative approach is to use animation frames as shown here: https://plotly.com/python/animations/ (halfway, under "Simple Play Button". But this requires all states (frames) to be defined defined beforehand, which can become a huge matrix if you have a lot of data. But it would work. This does work in a browser windows as well. – StephanT Jul 05 '23 at 07:33
  • thank you for ur time and efford. After investigating ur suggestions, I's able to get more from the documentation than before. I's missing concepts like "full HTML render", "supporting Python code". I have read some python books/courses but they explain the basics (if, for, def, class) but lack a dipper understanding. Blog (like stackoverflow) help but this is more to answer a specific problem than to explain the concepts. Any book or course you will suggest, not all, but to get to a next level ("understand python engine")? I feel lime missing something but not sure how to approach. – Almodius Jul 05 '23 at 09:20
  • For your problem it's most important to understand where code "lives". A browser is not capable of running Python. Plotly creates an HTML graph ("website code") including all connected data and Plotly functions in HTML code, which is shown in the browser. Other Python code that you may be using surrounding the creation of the graph is not translated by Plotly and not given to the "website" you are viewing and the "connection" to the rest of the Python code is broken. If you let Plotly show the graph in VS Code (or JupyterLab), that connection remains intact. – StephanT Jul 05 '23 at 12:15