1
+ import streamlit as st
2
+ import pandas as pd
3
+ import matplotlib .pyplot as plt
4
+ import seaborn as sns
5
+ import geopandas as gpd
6
+ import plotly .express as px
7
+
8
+ energy_columns = ['renewables_electricity' , 'coal_electricity' , 'gas_electricity' , 'oil_electricity' , 'nuclear_electricity' , 'wind_electricity' , 'solar_electricity' , "hydro_electricity" ]
9
+ # Load and prepare data
10
+ @st .cache_data
11
+ def load_data ():
12
+ url = "https://raw.githubusercontent.com/owid/energy-data/master/owid-energy-data.csv"
13
+ df = pd .read_csv (url )
14
+ df ['year' ] = pd .to_datetime (df ['year' ], format = '%Y' )
15
+ df .rename (columns = {
16
+ "renewables_electricity" : "Renewables" ,
17
+ "hydro_electricity" : "Hydro" ,
18
+ "solar_electricity" : "Solar" ,
19
+ "wind_electricity" : "Wind" ,
20
+ "coal_electricity" : 'Coal' ,
21
+ 'gas_electricity' : "Gas" ,
22
+ 'oil_electricity' : "Oil" ,
23
+ 'nuclear_electricity' : "Nuclear"
24
+ }, inplace = True )
25
+
26
+ df = df [~ df .country .isin ([
27
+ "G20 (Ember)" ,
28
+ "OECD (Ember)" ,
29
+ "Asia (Ember)" ,
30
+ "G7 (Ember)" ,
31
+ "OECD (EI)" ,
32
+ "Asia Pacific (EI)" ,
33
+ "High-income countries" ,
34
+ "Europe (Ember)" ,
35
+ "Non-OECD (EI)" ,
36
+ "Asia" ,
37
+ "North America (Ember)" ,
38
+ "Upper-middle-income countries" ,
39
+ "Europe (EI)" ,
40
+ "Oceania (Ember)" ,
41
+ "ASEAN (Ember)" ,
42
+ "Lower-middle-income countries" ,
43
+ "European Union (27)" ,
44
+ "North America (EI)"
45
+ ])]
46
+
47
+ return df .sort_values ('year' )
48
+
49
+
50
+ @st .cache_data
51
+ def load_world_data (map_data ):
52
+ world = gpd .read_file ("ne_110m_admin_0_countries/ne_110m_admin_0_countries.dbf" )
53
+ # data processing
54
+ world .rename (columns = {"ADMIN" : "country" }, inplace = True )
55
+ # replace country name to fit the other dataset
56
+ world .country = world .country .replace (
57
+ ["United States of America" , "Democratic Republic of the Congo" , "Republic of the Congo" , "United Republic of Tanzania" , "The Bahamas" , "Czechia" , "eSwatini" , "Republic of Serbia" ],
58
+ ["United States" , "Democratic Republic of Congo" , "Congo" , "Tanzania" , "Bahamas" , "Czechoslovakia" , "Eswatini" , "Serbia" ]
59
+ )
60
+
61
+ # world.SOV_A3 = world.SOV_A3.replace(["US1", "CH1", "FR1", "KA1", "GB1", "NZ1", "AU1"], ["USA", "CHN", "FRA", "KAZ", "GBR", "NZL", "AUS"])
62
+ # latest_year = recent_data['year'].max() - pd.Timedelta(days=365*2)
63
+ # latest_data = recent_data[recent_data['year'] == latest_year]
64
+ world = world .merge (map_data , on = ['country' ])
65
+ return world
66
+
67
+
68
+ @st .cache_data
69
+ def get_map_plot (energy_type_map , year_map ):
70
+ match energy_type_map :
71
+ case "Solar" :
72
+ color_scale = "Oranges"
73
+ case "Wind" :
74
+ color_scale = "Greens"
75
+ case "Hydro" :
76
+ color_scale = "Blues"
77
+ case _ :
78
+ color_scale = "Viridis"
79
+
80
+ fig = px .choropleth (world , locations = 'ADM0_A3' , color = energy_type_map ,
81
+ hover_name = 'country' , projection = 'natural earth2' , color_continuous_scale = color_scale ,
82
+ title = f'{ energy_type_map .replace ("_" , " " ).title ()} Production in { year_map } ' )
83
+
84
+ return fig
85
+ df = load_data ()
86
+
87
+
88
+ # Streamlit app
89
+ st .title ('Global Energy Production Analysis' )
90
+ # st.write(df.columns)
91
+ # st.write([col.split("_")[0].capitalize() for col in energy_columns])
92
+ # Sidebar for user input
93
+ st .sidebar .header ('Filter Data' )
94
+ start_year = st .sidebar .slider ('Start Year' , 1900 , 2023 , 1980 )
95
+ end_year = st .sidebar .slider ('End Year' , 1900 , 2022 , 2023 )
96
+
97
+ # Filter data based on selected years
98
+ filtered_df = df [(df ['year' ].dt .year >= start_year ) & (df ['year' ].dt .year <= end_year )]
99
+
100
+ # Global trend plot
101
+ st .header ('Global Energy Production Trends' )
102
+ energy_types = st .multiselect (
103
+ 'Select Energy Types' ,
104
+ [col .split ("_" )[0 ].capitalize () for col in energy_columns ],
105
+ default = ["Solar" , "Wind" , "Hydro" ]
106
+ )
107
+
108
+ global_trend = filtered_df .groupby ('year' )[energy_types ].mean ()
109
+
110
+ fig = px .line (global_trend .reset_index (), x = 'year' , y = energy_types ,
111
+ title = 'Global Energy Production Trends' )
112
+ fig .update_yaxes (title = "Electricity Production (TWh)" )
113
+ st .plotly_chart (fig )
114
+
115
+ # Map of energy production
116
+ st .header ('Energy Production Map' )
117
+ energy_type_map = st .selectbox ('Select Energy Type for Map' , energy_types )
118
+ year_map = st .slider ('Select Year for Map' , start_year , end_year , end_year - 10 )
119
+
120
+
121
+ map_data = filtered_df [filtered_df ['year' ].dt .year == year_map ]
122
+ world = load_world_data (map_data )
123
+
124
+ fig = get_map_plot (energy_type_map , year_map )
125
+ fig .update_layout (margin = {"r" :0 ,"t" :0 ,"l" :0 ,"b" :0 })
126
+ st .plotly_chart (fig )
127
+
128
+ # Top countries comparison
129
+ st .header ('Top Countries Comparison' )
130
+ n_countries = st .slider ('Number of top countries to compare' , 1 , 20 , 15 )
131
+ top_countries = filtered_df .groupby ('country' )[energy_types [0 ]].mean ().nlargest (n_countries ).index .tolist ()
132
+
133
+ st .write (top_countries )
134
+
135
+ top_countries_data = filtered_df [filtered_df ['country' ].isin (top_countries )]
136
+
137
+ fig = px .line (top_countries_data , x = 'year' , y = energy_types [0 ], color = 'country' ,
138
+ title = f'Top { n_countries } Countries in { energy_types [0 ].replace ("_" , " " ).title ()} Production' )
139
+ st .plotly_chart (fig )
140
+
141
+ # Energy mix comparison
142
+ st .header ('Energy Mix Comparison' )
143
+ selected_country = st .selectbox ('Select a Country' , df ['country' ].unique (), index = None )
144
+ if selected_country == None :
145
+ selected_country = "Italy"
146
+
147
+ country_data = filtered_df [filtered_df ['country' ] == selected_country ]
148
+ # st.write(country_data)
149
+
150
+
151
+ energy_mix = country_data [energy_types ]
152
+ energy_mix ['year' ] = country_data .year
153
+
154
+ fig = px .area (energy_mix .dropna (), x = 'year' , y = energy_types ,
155
+ title = f'Energy Mix for { selected_country } ' )
156
+ fig .update_yaxes (title = "Electricity Production (TWh)" )
157
+ st .plotly_chart (fig )
158
+ # st.write(energy_mix)
159
+
160
+
161
+ st .write ("""
162
+ This Streamlit app provides an interactive analysis of global energy production trends.
163
+ You can use the sidebar and various selectors to customize the visualizations and explore different aspects of energy production data.
164
+ """ )
0 commit comments