How To Use Python Streamlit Library To Make Data Visualization Web Pages

When you think of Web pages, the first things that probably come to mind are HTML, CSS or JavaScript. This tutorial will show you how to create a data visualization web page in Python using the StreamLit library. It can easily convert an Excel data file into a Web page for all to view online. In this way, whenever you change and save the excel file, the web page can be updated in real time, which is really good.

1. Install Python Streamlit Library.

  1. Run the command $ pip install streamlit in a terminal to install the python streamlit library.
  2. Run the command $ pip show streamlit to see it’s installation related information.
    $ pip show streamlit
    Name: streamlit
    Version: 0.82.0
    Summary: The fastest way to build data apps in Python
    Home-page: https://streamlit.io
    Author: Streamlit Inc
    Author-email: [email protected]
    License: Apache 2
    Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
    Requires: validators, toml, pydeck, gitpython, click, astor, pillow, cachetools, python-dateutil, requests, numpy, blinker, tzlocal, tornado, protobuf, pyarrow, packaging, base58, altair, pandas
    Required-by: 
    
  3. Run the command $ pip install plotly_express==0.4.0 to install the python Plotly Express library.
  4. Run the command $ pip install xlrd==1.2.0 to install the python xlrd library. Because our data files are in xlsx format, the latest version of xlrd only supports xls files, So you need to specify the xlrd version as 1.2.0, so that pandas can successfully read the data. If your python xlrd version is not 1.2.0, when you run the app you will encounter below error message.
    ValueError: Your version of xlrd is 2.0.1. In xlrd >= 2.0, only the xls format is supported. Install openpyxl instead.
  5. To fix this error run the command $ pip install openpyxl to install the python openpyxl library.
    $ pip install openpyxl
    Collecting openpyxl
      Downloading openpyxl-3.0.7-py2.py3-none-any.whl (243 kB)
         |████████████████████████████████| 243 kB 220 kB/s 
    Collecting et-xmlfile
      Downloading et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)
    Installing collected packages: et-xmlfile, openpyxl
    Successfully installed et-xmlfile-1.1.0 openpyxl-3.0.7
    
  6. After you install the python streamlit library, you can run the command $ streamlit hello to run the hello world example.
    (env_ipython_example) songs-MacBook-Pro:csv2excel songzhao$ streamlit hello
    
      👋 Welcome to Streamlit!
    
      If you're one of our development partners or you're interested in getting
      personal technical support or Streamlit updates, please enter your email
      address below. Otherwise, you may leave the field blank.
    
      👋 Welcome to Streamlit!
    
      If you're one of our development partners or you're interested in getting
      personal technical support or Streamlit updates, please enter your email
      address below. Otherwise, you may leave the field blank.
    
      Email: [email protected]
    
      Privacy Policy:
      As an open source project, we collect usage statistics. We cannot see and do
      not store information contained in Streamlit apps. You can find out more by
      reading our privacy policy at: https://streamlit.io/privacy-policy
    
      If you'd like to opt out of usage statistics, add the following to
      ~/.streamlit/config.toml, creating that file if necessary:
    
        [browser]
        gatherUsageStats = false
    
    
      Welcome to Streamlit. Check out our demo in your browser.
    
      Local URL: http://localhost:8501
      Network URL: http://192.168.31.31:8501
    
      Ready to create your own Python apps super quickly?
      Head over to https://docs.streamlit.io
    
      May you create awesome apps!
    
    
      For better performance, install the Watchdog module:
    
      $ xcode-select --install
      $ pip install watchdog
  7. When the above command execute successfully, it will open a web browser and browse the web page with URL http://localhost:8501/.

2. How To Use Python Streamlit To Display Visualization Data In A Web Page.

  1. Create a folder with the name csv2exce.
  2. Create a python module file StreamlitExample.py and add below python source code in it.
    import pandas as pd
    import streamlit as st
    import plotly.express as px
    from PIL import Image
    
    def streamlit_example():
        # set web page title.
        st.set_page_config(page_title='Streamlit Example Title')
        
        # set web page header.
        st.header('Streamlit Example Header')
    
        # set web page sub title.
        st.subheader('This is a streamlit example to tell you how to use the streamlit library. ')
    
    if __name__ == '__main__':
        
        streamlit_example()
  3. Run the command $ streamlit run StreamlitExample.py to start the streamlit webserver and browse the URL http://localhost:8501/ to see the web page.
  4. You can run the below source code to create a bar chart.
    import pandas as pd
    import streamlit as st
    import plotly.express as px
    from PIL import Image    
        
    def streamlit_special_excel():
        
        # read data from the excel file.
        excel_file = 'employee_info.xlsx'
        sheet_name = 'sheet_1'
    
        df = pd.read_excel(excel_file,
                       sheet_name=sheet_name,
                       usecols='B:D',
                       header=0)
    
        
        df_participants = pd.read_excel(excel_file,
                                    sheet_name=sheet_name,
                                    usecols='F:G',
                                    header=3)
        df_participants.dropna(inplace=True)
    
        # Multiple choice of streamlit (option data)
        name = df['Name'].unique().tolist()
    
        # Streamlit's slider (salary data)
        salary = df['Salary'].unique().tolist()
        
        # Slider, maximum, minimum, interval value
        salary_selection = st.slider('Salary:',
                              min_value=min(salary),
                              max_value=max(salary),
                              value=(min(salary), max(salary)))
    
        # Multiple selection, select all by default
        name_selection = st.multiselect('Name:',
                                          salary,
                                          default=salary)
        
        # Filter data based on Selection
        mask = (df['Salary'].between(*salary_selection)) & (df['Name'].isin(name_selection))
        number_of_result = df[mask].shape[0]
    
        # According to the filter conditions, get valid data
        st.markdown(f'*有效数据: {number_of_result}*')
    
        # Group data according to selection
        df_grouped = df[mask].groupby(by=['Salary']).count()[['Name']]
        df_grouped = df_grouped.rename(columns={'Name': 'Counter'})
        df_grouped = df_grouped.reset_index()
        
        # Draw a histogram, configure related parameters
        bar_chart = px.bar(df_grouped,
                       x='Salary',
                       y='Counter',
                       text='Counter',
                       color_discrete_sequence=['#F63366']*len(df_grouped),
                       template='plotly_white')
        st.plotly_chart(bar_chart)
            
    
    if __name__ == '__main__':
        
        streamlit_special_excel()
  5. In addition, python streamlit can also add pictures and interactive tables to web pages.
    # Add pictures and interactive tables
    col1, col2 = st.beta_columns(2)
    image = Image.open('python.jpg')
    col1.image(image,
               caption='Designed by richard',
               use_column_width=True)
    col2.dataframe(df[mask], width=300)
  6. Draw pie chard.
    # Draw pie chart.
    pie_chart = px.pie(df_participants,
                       title='Total number of participants',
                       values='Number of people',
                       names='Company department')
    st.plotly_chart(pie_chart)

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Clicky