# Streamlit live updating plot

**URL:** <https://discuss.streamlit.io/t/streamlit-live-updating-plot/56023>\
**Category:** Using Streamlit\
**Created:** [November 23, 2023, 9:17am UTC](https://discuss.streamlit.io/t/streamlit-live-updating-plot/56023 "2023-11-23T09:17:48Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![darynella2001](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/darynella2001/32/34897_2.png) [@darynella2001](https://discuss.streamlit.io/u/darynella2001)\
**Post date:** [November 23, 2023, 9:17am UTC](https://discuss.streamlit.io/t/streamlit-live-updating-plot/56023/1 "2023-11-23T09:17:48Z")

</div>

Hello!  
I am working on a Streamlit app which goal is to have a figure with live-updating data. To give more context, I sniff some network packets and I want to plot them in a graph/figure/plot. Also, I want to refresh and re-plot the data every X amount of time. (let’s say every 1s). How can I do it. Until now, my code plots one figure per sniffed packet.

```auto
import streamlit as st
import psutil
from scapy.all import *
import matplotlib.pyplot as plt

timestamps = []
packet_sizes = []
fig, ax = plt.subplots()
line, = ax.plot([], [], label='Packet Size')

def get_interface_details(interface):
    try:
        addresses = psutil.net_if_addrs()
        if interface in addresses:
            ip_address = addresses[interface][0].address
            netmask = addresses[interface][0].netmask
            details = f"Interface: {interface}\nIP Address: {ip_address}\nNetmask: {netmask}"
            return details
    except:
        return interface

def get_available_interfaces():
    interfaces = []
    for interface, addresses in psutil.net_if_addrs().items():
        if interface != "lo":
            interface_details = get_interface_details(interface)
            interfaces.append(interface_details)
    return interfaces

def packet_handler(packet):
    if Dot1Q in packet and packet[Dot1Q].prio==7:
        packet_len = len(packet)
        packet_time = packet.time
        update_plot(packet_time, packet_len)

    st.pyplot(fig)

def start_sniffing(interface):
    st.write("Starting packet capture on interface", interface)
    sniff(iface=interface, prn=packet_handler)

def update_plot(timestamp, packet_size):
    timestamps.append(timestamp)
    packet_sizes.append(packet_size)
    line.set_xdata(timestamps)
    line.set_ydata(packet_sizes)
    ax.relim()
    ax.autoscale_view()

def main():
    st.set_page_config(page_title="Network Analyzer (Protocol & Speed Test)")
    st.title("Network Analyzer (Protocol & Speed Test)")
    # Add custom CSS style for the page background
    page_bg_img = '''
    <style>
    .stApp {
        backgrou-color:white;
        background-size: cover;
    }
    </style>
    '''
    
    st.markdown(page_bg_img, unsafe_allow_html=True)
    interfaces = get_available_interfaces()
    if not interfaces:
        st.error("No network interfaces found.")
        return

   
    selected_interface = st.selectbox("Select an interface", interfaces, format_func=lambda x: x.replace('\n', ', '))

    if st.button("Start Capture"):
        interface_name = selected_interface.split('\n')[0].split(": ")[1] # Extract the interface name from the selected option
        start_sniffing(interface_name)
        
if __name__ == " __main__":
    main()

```

---

<div class="post-metadata">

**Author:** ![dataprofessor](https://sea2.discourse-cdn.com/streamlit/user_avatar/discuss.streamlit.io/dataprofessor/32/44163_2.png) [@dataprofessor](https://discuss.streamlit.io/u/dataprofessor)\
**Post date:** [November 23, 2023, 2:43pm UTC](https://discuss.streamlit.io/t/streamlit-live-updating-plot/56023/2 "2023-11-23T14:43:21Z")

</div>

Hi @darynella2001

You could make use of the `sleep` method from the `time` module together with a for loop to iteratively update the plot every N seconds (e.g. `time.sleep(1)`)

Here are some relevant posts to get you started:

> **[How to update a plot on same figure during the loop? - GeeksforGeeks](https://www.geeksforgeeks.org/how-to-update-a-plot-on-same-figure-during-the-loop/)**
>
> A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

> [@Reload altair chart when new data is added to df](https://discuss.streamlit.io/t/reload-altair-chart-when-new-data-is-added-to-df/7668/3):
>
> Hi, I am not sure how to “call chart on that frame”, would u be able to show a code snippet? this is my current code for st.line\_chart for reloading the chart based on new updates of rows. cpu\_chart = st.line\_chart(df height=250) for i in range(100): cpu\_chart.add\_rows(df2) For altair, a code like this wouldnt work as it will create a new frame every iteration. numpy as np import altair as alt df = pd.DataFrame( np.random.randn(100, 3), columns=['a', 'b', 'c']) c = alt.Chart(d…

> [@How to animate a line chart](https://discuss.streamlit.io/t/how-to-animate-a-line-chart/164/2):
>
> Hi @cristian.cotoi! Welcome to the Streamlit community! hugs It is absolutely possible to animate matplotlib charts in Streamlit. I’ve modified your code in [this gist](https://gist.github.com/treuille/4f70bff85ec5856cc7696f5c73f1ea11): import matplotlib.pyplot as plt import numpy as np import streamlit as st import time fig, ax = plt.subplots() max\_x = 5 max\_rand = 10 x = np.arange(0, max\_x) ax.set\_ylim(0, max\_rand) line, = ax.plot(x, np.random.randint(0, max\_rand, max\_x)) the\_plot = st.pyplot(plt) def init(): # give a clean slate to start line.set\_…

This blog also has an example that you can use a starter idea:

> **[How to build a real-time live dashboard with Streamlit](https://blog.streamlit.io/how-to-build-a-real-time-live-dashboard-with-streamlit/)**
>
> 5 easy steps to make your own data dashboard

Hope these helps!

---

<div class="post-metadata">

**Author:** ![system](https://global.discourse-cdn.com/streamlit/original/3X/c/f/cf4c2ee0d938358f82448c5fe4b9c3c91d7ce19c.svg) [@system](https://discuss.streamlit.io/u/system)\
**Post date:** [May 21, 2024, 2:44pm UTC](https://discuss.streamlit.io/t/streamlit-live-updating-plot/56023/3 "2024-05-21T14:44:12Z")

</div>

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.
