0

Goal

I want to continuously update a plotnine plot on a streamlit app.

Code

I receive data from socket and then plot it as follows:

import socket
import struct
import pandas as pd
import streamlit as st
import time
from plotnine import *



UDP_IP = "127.0.0.1"
UDP_PORT = 9000

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    time.sleep(0.1)
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    fields = struct.unpack_from('=ddd', data)
    
    d = {'y': fields[0],
         'x': fields[1],
         'z': fields[2]}

    dff = pd.DataFrame([d], columns=d.keys())
  

    # creating a single-element container.
    # placeholder = st.empty()
   
    # with placeholder.container():
    st.markdown("### First Chart")
    fig = ggplot(dff, aes("x", "y")) + geom_point()
    st.pyplot(ggplot.draw(fig))

Problem

But the code above (with or without st.empty placeholder) produces the following plot. I want to keep just one plot and want to update the point position on it. How can I achieve that?

enter image description here

umair durrani
  • 5,597
  • 8
  • 45
  • 85

1 Answers1

1

I think that an idea can be to upload the stramlit file like suggested in How to make Streamlit reloads every 5 seconds?. You can try an example that increase each seconds (but you substitute the add operation with yours), I put it into refresher.py:

from random import randint
import time
import os
def refresher(seconds):
    x = 0
    while True:
        mainDir = os.path.dirname(__file__)
        filePath = os.path.join(mainDir, 'test.py')
        x += 1
        # write (or upload) your streamlit file
        with open(filePath, 'w') as f:
            f.write(f'import streamlit as st\nst.title("# {x}")')
        time.sleep(seconds)
refresher(1)

Now you can run:

# terminal 1
python refresher.py
# terminal 2
streamlit run test.py

Now you can open your browser on streamlit URL (http://localhost:8501/) and click on Always rerun (this need the newest version of streamlit maybe). You will see the increment autoreload the steamlit page.

enter image description here

Nicola Landro
  • 336
  • 3
  • 17