File size: 6,074 Bytes
c7d12d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import streamlit as st
import pandas as pd
import plotly.express as px 
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import numpy as np


### CONFIG
st.set_page_config(
    page_title="Air-Quality",
    page_icon="🌡️",
    layout="wide"
  )

### TITLE AND TEXT
st.title("Air Quality.")
@st.cache # this lets the 
def def_load():
    df = pd.read_csv('AirQuality.xls', sep=';')
    df.dropna(axis=0, how='all', inplace=True)
    df = df.iloc[:,0:-2] # Two col unnamed are dropped
    # Concaténer les colonnes "Date" et "Time" en une seule colonne "Datetime"
    df["Datetime"] = pd.to_datetime(df["Date"] + " " + df["Time"], format="%d/%m/%Y %H.%M.%S")

    # Supprimer les anciennes colonnes si besoin
    df.drop(columns=["Date", "Time"], inplace=True)    

    for col in df.columns[:-2]:
        if df[col].dtype == 'object':
            df[col] = df[col].map(lambda x: x.replace(',', '.')).astype(float)
    return df


data_load_state = st.text('Loading data...')
data = def_load()

data_load_state.text("") # change text from "Loading data..." to "" once the the load_data function has run

## Run the below code if the check is checked ✅
if st.checkbox('Show raw data'):
    st.subheader('Raw data')
    st.write(data) 



# col1, col2 = st.columns(2)

# with col1:
#     a = 5
#     st.write(a)
# with col2:
#     with st.form("average_sales_per_country"):
#         submit = st.form_submit_button("submit")
#         if submit:
#             a += 1
#     # a = 10
#     st.write(a)

#### CREATE TWO COLUMNS
col1, col2 = st.columns(2)

# Initialize plot_data with all data
plot_data = data.copy()

# Define the form first, so we can use the results in both columns
with col2:
    st.markdown("**2️⃣ Example of input form**")
    with st.form("average_sales_per_country"):
        start_period = st.date_input("Select a start date you want to see your metric")
        end_period = st.date_input("Select an end date you want to see your metric")
        submit = st.form_submit_button("submit")
    
    # Create the mask when form is submitted
    if submit:
        start_period, end_period = pd.to_datetime(start_period), pd.to_datetime(end_period)
        mask = (data["Datetime"] > start_period) & (data["Datetime"] < end_period)
        plot_data = data[mask]
        st.write(f"Points in selected range: {mask.sum()}")

# Now use plot_data (which may be filtered) for plotting
with col1:
    st.markdown("** Example of input widget**")
    df = plot_data.copy()  # Use plot_data instead of data
    
    if df['T'].dtype == 'object':
        df['T'] = df['T'].map(lambda x: x.replace(',', '.')).astype(float)
    T_mask = df['T'] > 0
    
    if df['RH'].dtype == 'object':
        df['RH'] = df['RH'].map(lambda x: x.replace(',', '.')).astype(float)
    RH_mask = df['RH'] > 0
    
    # Create figure with secondary y-axis
    fig = make_subplots(specs=[[{"secondary_y": True}]])
    
    # Add traces
    fig.add_trace(
        go.Line(x=df['Datetime'], y=df['T'][T_mask], name="T(°C)"),
        secondary_y=False,
    )
    fig.add_trace(
        go.Line(x=df['Datetime'], y=df['RH'][RH_mask], name="H(%)."),
        secondary_y=True,
    )
    
    # Add figure title
    fig.update_layout(
        title_text="Temperature and Humidity "
    )
    
    # Set x-axis title
    fig.update_xaxes(title_text="Time --->")
    
    # Set y-axes titles
    fig.update_yaxes(title_text="<b>Temperature</b> (°C)", secondary_y=False)
    fig.update_yaxes(title_text="<b>Humidity</b>(%)", secondary_y=True)
    
    st.plotly_chart(fig, use_container_width=True)


    pol = st.selectbox("Select a c", data.drop(["Datetime", "T", "RH", 'AH'], axis=1).columns)


# st.markdown("""
#     Welcome to this awesome `streamlit` dashboard. This library is great to build very fast and
#     intuitive charts and application running on the web. Here is a showcase of what you can do with
#     it. Our data comes from an e-commerce website that simply displays samples of customer sales. Let's check it out.
#     Also, if you want to have a real quick overview of what streamlit is all about, feel free to watch the below video 👇
# """)


# @st.cache # this lets the 
# def load_data(nrows):
#     data = pd.read_csv(DATA_URL, nrows=nrows)
#     data["Date"] = data["Date"].apply(lambda x: pd.to_datetime(",".join(x.split(",")[-2:])))
#     data["currency"] = data["currency"].apply(lambda x: pd.to_numeric(x[1:]))
#     return data

# data_load_state = st.text('Loading data...')
# data = load_data(1000)
# data_load_state.text("") # change text from "Loading data..." to "" once the the load_data function has run

# ## Run the below code if the check is checked ✅
# if st.checkbox('Show raw data'):
#     st.subheader('Raw data')
#     st.write(data) 


# ### SIDEBAR
# st.sidebar.header("Build dashboards with Streamlit")
# st.sidebar.markdown("""
#     * [Load and showcase data](#load-and-showcase-data)
#     * [Charts directly built with Streamlit](#simple-bar-chart-built-directly-with-streamlit)
#     * [Charts built with Plotly](#simple-bar-chart-built-with-plotly)
#     * [Input Data](#input-data)
# """)
# e = st.sidebar.empty()
# e.write("")
# st.sidebar.write("Made with 💖 by [Jedha](https://jedha.co)")

# ### EXPANDER

# with st.expander("⏯️ Watch this 15min tutorial"):
#     st.video("https://youtu.be/B2iAodr0fOo")

# st.markdown("---")

# #### CREATE TWO COLUMNS
# col1, col2 = st.columns(2)

# with col1:
#     st.markdown("First column")
#     country = st.selectbox("Select a country you want to see all time sales", data["country"].sort_values().unique())

# with col2:
#     st.markdown("Second column")
#     with st.form("average_sales_per_country"):
#       country = st.selectbox("Select a country you want to see sales", data["country"].sort_values().unique())
#       start_period = st.date_input("Select a start date you want to see your metric")
#       end_period = st.date_input("Select an end date you want to see your metric")
#       submit = st.form_submit_button("submit")