|
1 | | -from shiny import App, render, ui |
| 1 | +import datetime |
| 2 | +import pandas as pd |
| 3 | +import plotly.graph_objects as go |
| 4 | +import requests |
2 | 5 |
|
3 | | -app_ui = ui.page_fluid( |
4 | | - ui.panel_title("Hello Shiny!"), |
5 | | - ui.input_slider("n", "N", 0, 100, 20), |
6 | | - ui.output_text_verbatim("txt"), |
| 6 | +from shiny import App, render, ui, reactive |
| 7 | +from shinywidgets import render_widget, output_widget |
| 8 | + |
| 9 | +app_ui = ui.page_sidebar( |
| 10 | + ui.sidebar( |
| 11 | + ui.input_numeric("lat", |
| 12 | + "Latitude", |
| 13 | + value = 51.3167), |
| 14 | + ui.input_numeric("lon", |
| 15 | + "Longitude", |
| 16 | + value = 9.5) |
| 17 | + ), |
| 18 | + output_widget("plot"), |
| 19 | + ui.output_table("table"), |
| 20 | + title = "Weather App" |
7 | 21 | ) |
8 | 22 |
|
9 | 23 |
|
10 | 24 | def server(input, output, session): |
11 | | - @render.text |
12 | | - def txt(): |
13 | | - return f"n*2 is {input.n() * 2}" |
| 25 | + @reactive.Calc |
| 26 | + def weather_dat(): |
| 27 | + url = f"https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s&hourly=temperature_2m,rain&past_days=3" %(input.lat(), input.lon()) |
| 28 | + response = requests.get(url) |
| 29 | + data = response.json()["hourly"] |
| 30 | + df = pd.DataFrame(data) |
| 31 | + return df |
| 32 | + |
| 33 | + @render_widget |
| 34 | + def plot(): |
| 35 | + df = weather_dat() |
| 36 | + fig = go.Figure() |
| 37 | + fig.add_trace(go.Scatter(x=df['time'], y=df['temperature_2m'], mode='lines', name='Temperature')) |
| 38 | + fig.add_trace(go.Bar(x=df['time'], y=df['rain'], name='Rain', yaxis='y2')) |
| 39 | + fig.add_vline(x = datetime.datetime.today()) |
| 40 | + fig.update_layout( |
| 41 | + xaxis_title='Date', |
| 42 | + yaxis_title='Temperature (°C)', |
| 43 | + yaxis2=dict( |
| 44 | + title='Rain (mm)', |
| 45 | + overlaying='y', |
| 46 | + side='right' |
| 47 | + ), |
| 48 | + showlegend = False |
| 49 | + ) |
| 50 | + return fig |
| 51 | + |
| 52 | + @render.table(index= True) |
| 53 | + def table(): |
| 54 | + df = weather_dat() |
| 55 | + df['time'] = pd.to_datetime(df['time']) |
| 56 | + df.set_index('time', inplace=True) |
| 57 | + daily_summary = df.resample('D').agg({ |
| 58 | + 'temperature_2m': ['min', 'max'], |
| 59 | + 'rain': 'sum' |
| 60 | + }) |
| 61 | + daily_summary = daily_summary.T |
| 62 | + daily_summary.index = ['min. T (°C)', 'max. T (°C)', 'Rain (mm)'] |
| 63 | + daily_summary.columns = [col.strftime('%d.%m') for col in daily_summary.columns] |
| 64 | + return daily_summary |
| 65 | + |
| 66 | + |
14 | 67 |
|
15 | 68 |
|
16 | 69 | app = App(app_ui, server) |
0 commit comments