Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
120 views

Dashboard Python

This document describes how to create a live dashboard using Python and the Streamlit library. It provides functions to analyze data like calculating distributions, plotting time series, and relating variables. It then shows how to build the dashboard interface in Streamlit with components like selections, text inputs, columns, and displaying results. The goal is to create an interactive dashboard for exploring and visualizing data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
120 views

Dashboard Python

This document describes how to create a live dashboard using Python and the Streamlit library. It provides functions to analyze data like calculating distributions, plotting time series, and relating variables. It then shows how to build the dashboard interface in Streamlit with components like selections, text inputs, columns, and displaying results. The goal is to create an interactive dashboard for exploring and visualizing data.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

1 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

data = pd.read_csv('data.csv')

2 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

def get_distribution(data, column_name):

values = data[column_name].tolist()

distribution = {}
total = 0
for value in values:
total = total + 1
if value not in distribution:
distribution[value] = 1
else:
distribution[value] = distribution[value] + 1

3 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

for key in distribution:


distribution[key] = distribution[key] / total * 100

df = pd.DataFrame.from_dict(distribution,orient='index')
df = df.rename(columns = {0:'Percentage'})

return df

get_distribution(data, ‘Gender')

+========+============+
| - | Percentage |
+========+============+
| Female | 0.501 |
+--------+------------+
| Male | 0.499 |
+--------+------------+

def get_signups(data, start, end):

dates = []

delta = relativedelta(end, start)


nr_months = delta.months + delta.years * 12
current_date = start
for i in range(nr_months):
dates.append(current_date)

4 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

current_date = current_date + relativedelta(months=1)

count = np.zeros_like(dates,dtype=int)
for date_str in data['Sign Up Date'].tolist():
date = dt.datetime.strptime(date_str, '%Y-%m-%d')
for i in range(len(dates)):
if date.month == dates[i].month and date.year ==
dates[i].year:
count[i] = count[i] + 1

df = pd.DataFrame({'Dates':dates, 'Count':count})
df = df.set_index('Dates')

return df

def accumulated_signups(df):

new_df = df.copy()
total = 0
for index, row in df.iterrows():
total = total + row['Count']
new_df.at[index, 'Count'] = total

new_df = new_df.rename(columns = {'Count':'Accumulated count'})


return new_df

def relate_data(data, key_variable, value_variable):

keys = data[key_variable]
values = data[value_variable]

5 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

info = {}
aux = {} # to hold all the values to compute the mean
for key, value in zip(keys, values):
if key in info:
aux[key].append(value)
info[key][0] = np.around(np.mean(aux[key]),2)

else:
info[key] = [[]]
aux[key] = []

df = pd.DataFrame.from_dict(info,orient='index')
df = df.rename(columns = {0:value_variable})
return df

relate_data(data, ‘Profession', ‘Salary')

+============+=========+
| Profession | Salary |
+============+=========+
| Accountant | 2098.76 |
+------------+---------+
| Secretary | 2151.88 |
+------------+---------+
| Dentist | 2166.76 |
+------------+---------+
| ... | ... |
+------------+---------+

def generate_age_groups():
groups = {}
for i in range(0, 100):
groups[i] = math.floor(i/10)

return groups

6 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

def search(data, column, search_term):

if column == 'Age':
search_term = int(search_term)

indexes = data.loc[data[column].isin([search_term])].index
if indexes.size > 0:
return data.iloc[indexes]
else:
return []

search_result = search(data, ‘Country', ‘Portugal')

import streamlit as st

7 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

st.write("Hello")

streamlit run .\app_streamlit.py pip install

streamlit

st.markdown("<h1 style='text-align: center; color: black;'>My


Dashboard</h1>", unsafe_allow_html=True)

8 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

st.columns()

buffer, col2, col3, col4 = st.columns([1,4,4,2])

with col2:
st.write("This is in column 2")

with col3:
st.write("And column 3")

with col4:
st.write("This column is half the size of 2 and 3")

9 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

import pandas as pd

data = pd.read_csv(Path(__file__).parents[0]/'data.csv')
df = pd.DataFrame()

buffer, col2, col3 = st.columns([1, 5, 15])

with col2:
key = st.selectbox("Key",
['Name','Email','Age','Gender','Country','Sign Up Date',
'Profession','Salary'])

with col3:
search_term = st.text_input("Search")
if key != '' and search_term != '':
df = search(data, key, search_term)

buffer, col2 = st.columns([1, 20])

10 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

with col2:
if not df.empty:
st.dataframe(df)
else:
st.write('Did not find any person matching the criteria')

st.dataframe()

st.bar_chart()

11 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

st.markdown('***') #separator

buffer, col2, col3, col4 = st.columns([1,7,7,7])

with col2:
st.markdown("<h5 style='text-align: center; color: black;'>Gender
Distribution</h1>", unsafe_allow_html=True)

with col3:
st.markdown("<h5 style='text-align: center; color: black;'>Age
Distribution</h1>", unsafe_allow_html=True)
st.bar_chart(get_distribution(data, 'Age'))

with col4:
st.markdown("<h5 style='text-align: center; color:
black;'>Country Distribution</h1>", unsafe_allow_html=True)

12 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

def pie_chart(df):
labels = list(df.index)
values = list(df['Percentage'])

fig, ax = plt.subplots()
ax.pie(values,labels=labels, autopct='%1.1f%%')
ax.axis('equal') # Equal aspect ratio ensures that pie is drawn
as a circle.

ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)

return fig

st.markdown('***') #separator

buffer, col2, col3, col4 = st.columns([1,7,7,7])

with col2:
st.markdown("<h5 style='text-align: center; color: black;'>Gender
Distribution</h1>", unsafe_allow_html=True)

st.pyplot(pie_chart(get_distribution(data, 'Gender')))

with col3:
st.markdown("<h5 style='text-align: center; color: black;'>Age
Distribution</h1>", unsafe_allow_html=True)
st.bar_chart(get_distribution(data, 'Age'))

with col4:
st.markdown("<h5 style='text-align: center; color:
black;'>Country Distribution</h1>", unsafe_allow_html=True)

st.pyplot(pie_chart(get_distribution(data, 'Country')))

13 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

st.bar_chart()

st.markdown('***') #separator

buffer, col2, col3 = st.columns([1, 10, 10])

with col2:
st.markdown("<h5 style='text-align: center; color:
black;'>Average salary per profession</h1>", unsafe_allow_html=True)
st.bar_chart(relate_data(data, 'Profession', 'Salary'))

with col3:
st.markdown("<h5 style='text-align: center; color:
black;'>Average salary per age group</h1>", unsafe_allow_html=True)
st.bar_chart(relate_data(data, 'Age', 'Salary'))

14 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

st.line_chart()

st.markdown('***') #separator

buffer, col2 = st.columns([1, 20])

with col2:

15 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

st.markdown("<h5 style='text-align: center; color:


black;'>Accumulated signups over time</h1>", unsafe_allow_html=True)
st.line_chart(accumulated_signups(get_signups(data,
dt.datetime(2020, 1, 1), dt.datetime(2022,1,1))))

pipreqs /path/to

/project

pipreqs

pip install pipreqs

16 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

17 de 18 13/09/2022, 5:33
Create a Live Dashboard with Python and Streamlit | by Gonçalo Ch... https://medium.com/@goncalorrc/create-a-live-dashboard-with-pytho...

18 de 18 13/09/2022, 5:33

You might also like