Py.Cafe

Sindhup24/

solara-click-counter-0

Interactive Click Counter with Threshold Alert

DocsPricing
  • app.py
  • requirements.txt
  • solara-dropdown.csv
  • test_longtable_line.csv
app.py
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
183
184
185
186
187
188
189
190
191
192
193
import pandas as pd
import solara
import matplotlib.pyplot as plt
import numpy as np
import folium
from folium.plugins import TimestampedGeoJson

# Load the CSV files
file_path = 'solara-dropdown.csv'
id_file_path = 'test_longtable_line.csv'
data = pd.read_csv(file_path)
id_data = pd.read_csv(id_file_path)

# Extract unique states and IDs
unique_states = data['state'].unique().tolist()
unique_ids = id_data['Id'].unique().tolist()

# Merge the dataframes to ensure we have both IDs and other relevant data
merged_data = pd.merge(data, id_data, on='Id', how='inner')

# Reactive variables
selected_id = solara.reactive(unique_ids[0])
selected_state = solara.reactive("")
selected_name = solara.reactive("")
generate_trigger = solara.reactive(0)

# Function to update state and name based on selected ID
def update_state_and_name(id):
    filtered_data = merged_data[merged_data['Id'] == id]
    if not filtered_data.empty:
        selected_state.value = filtered_data['state'].iloc[0]
        selected_name.value = filtered_data['Name_x'].iloc[0]
    else:
        selected_state.value = ""
        selected_name.value = ""

# Function to filter data based on selected state and ID
def get_filtered_names(state, id):
    filtered_names = merged_data[(merged_data['state'] == state) & (merged_data['Id'] == id)]['Name_x'].unique().tolist()
    if filtered_names:
        selected_name.value = filtered_names[0]
    return filtered_names

# Function to plot bar chart using matplotlib
def plot_bar_chart(df, name):
    filtered_data = df[df['Name_x'] == name].drop_duplicates(subset=['XCoordinate_x', 'YCoordinate_x'])
    if filtered_data.empty:
        print("No data available for the selected filters.")
        return None
    fig, ax = plt.subplots(figsize=(10, 6))
    width = 0.3  # Bar width
    x = np.arange(len(filtered_data))  # the label locations
    ax.bar(x - width/2, filtered_data['XCoordinate_x'], width, label='XCoordinate', color='blue')
    ax.bar(x + width/2, filtered_data['YCoordinate_x'], width, label='YCoordinate', color='orange', alpha=0.7)
    ax.set_xticks(x)
    ax.set_xticklabels(filtered_data['Name_x'], rotation=45, ha='right')
    ax.set_xlabel('Name', fontweight='bold')
    ax.set_ylabel('Coordinate Value', fontweight='bold')
    ax.set_title(f'Bar Chart for {name}', fontweight='bold')
    ax.legend(loc='upper right')
    
    # Add data labels
    for i in range(len(filtered_data)):
        ax.text(i - width/2, filtered_data['XCoordinate_x'].iloc[i] / 2, str(filtered_data['XCoordinate_x'].iloc[i]), ha='center', va='bottom', color='white')
        ax.text(i + width/2, filtered_data['YCoordinate_x'].iloc[i] / 2, str(filtered_data['YCoordinate_x'].iloc[i]), ha='center', va='bottom', color='black')
    
    fig.tight_layout()  # Adjust layout to make room for rotated x-tick labels
    return fig

# Function to add legends to the map
def add_legend(m):
    legend_html = '''
     <div style="position: fixed; 
                 bottom: 50px; right: 50px; width: 150px; height: 150px; 
                 border:2px solid grey; z-index:9999; font-size:14px;
                 background-color:white;
                 ">
     &nbsp;<b>Legend</b><br>
     &nbsp;<i class="fa fa-circle" style="color:green"></i>&nbsp; value < 10<br>
     &nbsp;<i class="fa fa-circle" style="color:blue"></i>&nbsp; 10 <= value < 20<br>
     &nbsp;<i class="fa fa-circle" style="color:orange"></i>&nbsp; 20 <= value < 30<br>
     &nbsp;<i class="fa fa-circle" style="color:red"></i>&nbsp; value >= 30
     </div>
     '''
    m.get_root().html.add_child(folium.Element(legend_html))

# Function to plot map with timeline slider
def plot_map_with_slider(df, highlight_id=None):
    # Create a map centered around the mean coordinates with a specific zoom level
    m = folium.Map(location=[0, 20], zoom_start=4)
    
    # Define a function to determine color based on value
    def get_color(value):
        if value < 10:
            return 'green'
        elif 10 <= value < 20:
            return 'blue'
        elif 20 <= value < 30:
            return 'orange'
        else:
            return 'red'

    features = []
    for i, row in df.iterrows():
        feature = {
            'type': 'Feature',
            'geometry': {
                'type': 'Point',
                'coordinates': [row['XCoordinate_x'], row['YCoordinate_x']]
            },
            'properties': {
                'time': row['date'],
                'popup': f"ID: {row['Id']} - {row['Name_x']}: ({row['XCoordinate_x']}, {row['YCoordinate_x']}) Value: {row['value']}",
                'icon': 'circle',
                'iconstyle': {
                    'color': get_color(row['value']),
                    'fillColor': get_color(row['value']),
                    'fillOpacity': 0.6,
                    'radius': 10
                }
            }
        }
        if highlight_id and row['Id'] == highlight_id:
            # Adding blinking effect for the highlighted ID
            feature['properties']['iconstyle']['className'] = 'blinking'
        features.append(feature)
    
    TimestampedGeoJson({
        'type': 'FeatureCollection',
        'features': features
    }, period='P1D', add_last_point=True, auto_play=False, loop=False).add_to(m)

    # Add legend to the map
    add_legend(m)

    # Add CSS for blinking effect
    blinking_css = '''
    <style>
    .blinking {
        animation: blinker 1s linear infinite;
    }
    @keyframes blinker {
        50% { opacity: 0; }
    }
    </style>
    '''
    m.get_root().html.add_child(folium.Element(blinking_css))

    return m

# Components
@solara.component
def View():
    with solara.VBox() as main:
        if generate_trigger.value > 0 and selected_id.value:
            m = plot_map_with_slider(merged_data, highlight_id=selected_id.value)
            fig = plot_bar_chart(merged_data, selected_name.value)
            if fig:
                solara.HTML(tag="div", unsafe_innerHTML=m._repr_html_())
                solara.FigureMatplotlib(fig)
                solara.Info("Map and chart have been updated.")
            else:
                solara.Warning("No data available for the selected state and name.")
        else:
            m = plot_map_with_slider(merged_data)
            solara.HTML(tag="div", unsafe_innerHTML=m._repr_html_())
            solara.Warning("Please select a state and a name.")
    return main

@solara.component
def Controls():
    # Update the options for the Name dropdown based on the selected state and ID
    update_state_and_name(selected_id.value)
    filtered_names = get_filtered_names(selected_state.value, selected_id.value)
    
    solara.Select('ID', values=unique_ids, value=selected_id)
    solara.Select('State', values=unique_states, value=selected_state)
    solara.Select('Name', values=filtered_names, value=selected_name)
    
    def generate_chart():
        generate_trigger.value += 1

    solara.Button(label="Generate Chart", on_click=generate_chart, icon_name="mdi-chart-bar")

@solara.component
def Page():
    with solara.Sidebar():
        Controls()
    View()

# Display the page
Page()