-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path22082448.py
More file actions
361 lines (250 loc) 路 12.6 KB
/
Copy path22082448.py
File metadata and controls
361 lines (250 loc) 路 12.6 KB
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# -*- coding: utf-8 -*-
""" inZK00.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1-fZUpkC2cG0OlIgHnjpZCQ1fJXRBBZBU
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('sdg_index_2000-2022.csv')
df.head()
"""**Data:**
The sdg_index_2000-2022.csv dataset presents information on 193 UN Member States sustainability scores from 2000 to 2023 relating to 17 objectives for which the dataset has the following variables:
**country_code:** A unique identifier that links to the primary dataset.
**country:** The name of the country.
**year:** The year of the data entry.
**sdg_index_score:** The overall SDG (Sustainable Development Goals) index score of the country.
**goal_1_score:** The score for Goal 1: End poverty in all its forms everywhere.
**goal_2_score:** The score for Goal 2: End hunger, achieve food security and improved nutrition and promote sustainable agriculture.
**goal_3_score:** The score for Goal 3: Ensure healthy lives and promote well-being for all at all ages.
**goal_4_score:** The score for Goal 4: Ensure inclusive and equitable quality education and promote lifelong learning opportunities for all.
**goal_5_score:** The score for Goal 5: Achieve gender equality and empower all women and girls.
**goal_6_score:** The score for Goal 6: Ensure availability and sustainable management of water and sanitation for all.
**goal_7_score:** The score for Goal 7: Ensure access to affordable, reliable, sustainable and modern energy for all.
**goal_8_score:** The score for Goal 8: Promote sustained inclusive and sustainable economic growth, full and productive employment and decent work for all.
**goal_9_score:** The score for Goal 9: Build resilient infrastructure, promote inclusive and sustainable industrialization and foster innovation.
**goal_10_score:** The score for Goal 10: Reduce inequality within and among countries.
**goal_11_score:** The score for Goal 11: Make cities and human settlements inclusive, safe, resilient and sustainable.
**goal_12_score:** The score for Goal 12: Ensure sustainable consumption and production patterns.
**goal_13_score:** The score for Goal 13: Take urgent action to combat climate change and its impacts.
**goal_14_score:** The score for Goal 14: Conserve and sustainably use the oceans, seas and marine resources for sustainable development.
**goal_15_score:** The score for Goal 15: Protect, restore and promote sustainable use of terrestrial ecosystems,sustainably manage forests, combat desertification, and halt and reverse land degradation and halt biodiversity loss.
**goal_16_score:** The score for Goal 16: Promote peaceful and inclusive societies for sustainable development, provide access to justice for all and build effective, accountable
and inclusive institutions at all levels.
**goal_17_score:** The score for Goal 17: Strengthen the means of implementation and revitalize the Global Partnership for Sustainable Development.
"""
world_pop=pd.read_csv('world_population.csv')
world_pop.head()
import geopandas as gpd
# Load world map data
world_map = gpd.read_file(gpd.datasets.get_path("naturalearth_lowres"))
# Replace country names
country_replacements = {
"USA": "United States",
"Democratic Republic of the Congo": "Congo, Dem. Rep.",
"UK": "United Kingdom",
"Russia": "Russian Federation",
"Venezuela": "Venezuela, RB",
"Yemen": "Yemen, Rep."
}
world_map['name'] = world_map['name'].replace(country_replacements)
# Display the modified world map
print(world_map)
# Selecting columns CCA3 and Continent from world_pop
df_2 = world_pop[['CCA3', 'Continent']]
df_2.columns = ['country_code', 'Continent'] # Assigning column names to match the merge key
# Merging df_2 with sdg_index_2000_2022 on 'country_code'
sdg_index_2000_2022 = pd.merge(df, df_2, on='country_code')
# Display the resulting DataFrame
print(sdg_index_2000_2022)
# Grouping the data
grouped_data = sdg_index_2000_2022.groupby(['Continent', 'year']).agg(mean_c=('sdg_index_score', 'mean')).reset_index()
# Set a stylish seaborn theme
sns.set_theme(style="whitegrid")
# Choose a different color palette
colors = sns.color_palette("husl", n_colors=len(grouped_data['Continent'].unique()))
# Plotting using seaborn
plt.figure(figsize=(12, 8))
sns.lineplot(
data=grouped_data,
x='year',
y='mean_c',
hue='Continent',
palette=colors,
linewidth=2,
style='Continent',
markers=True,
markersize=8,
dashes=False,
)
# Updated X_label and Y_label titles for better understanding
plt.xlabel("Year", fontsize=14)
plt.ylabel("Average Sustainable Development Index Score", fontsize=14)
plt.title("Average SDG Index Score Across Continents (2000-2022)", fontsize=16)
plt.legend(title='Continent', loc='upper left', bbox_to_anchor=(1, 1))
# Adding grid for better readability
plt.grid(True, linestyle='--', alpha=0.7)
plt.savefig('/content/drive/MyDrive/line_plot1.png', bbox_inches='tight')
plt.show()
# Filter the data for the year 2022 and specified conditions for goal_1_score
filtered_data = sdg_index_2000_2022[(sdg_index_2000_2022['year'] == 2022) &
(sdg_index_2000_2022['goal_1_score'] < 70) &
(sdg_index_2000_2022['goal_1_score'] > 0)]
# Sort the data by 'goal_1_score' in descending order
filtered_data = filtered_data.sort_values(by='goal_1_score', ascending=False)
# Set a stylish seaborn theme
sns.set_theme()
# Define custom colors
continent_colors = {'Africa': '#FF7F0E', 'Asia': '#1F77B4', 'Europe': '#2CA02C', 'North America': '#9467BD',
'Oceania': '#8C564B', 'South America': '#E377C2'}
# Plotting using seaborn with customizations
plt.figure(figsize=(12, 8))
sns.barplot(
data=filtered_data,
x='goal_1_score',
y='country',
hue='Continent',
dodge=True,
palette=continent_colors,
edgecolor='black', # Add black borders to bars for better visibility
linewidth=1.5, # Increase bar linewidth
)
plt.title("Poverty per country in 2022", fontsize=16)
plt.xlabel("Goal 1 Score", fontsize=14)
plt.ylabel("Country", fontsize=14)
# Customize legend
plt.legend(title='Continent', title_fontsize='14', fontsize='12', loc='upper right')
# Display the plot
plt.show()
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Assuming you have already loaded the world_map GeoDataFrame and the sdg_index_2000_2022 DataFrame
# If not, you should load them first
# Print column names to check
print("world_map columns:", world_map.columns)
print("dataset columns:", dataset.columns)
# Create the dataset based on the provided R code
dataset = sdg_index_2000_2022[sdg_index_2000_2022['year'] == 2022][['country', 'goal_2_score']]
dataset.columns = ['name', 'goal_2_score'] # Change 'region' to 'name' to match world_map
# Merge the GeoDataFrame and DataFrame on the 'name' column
merged_data = gpd.pd.merge(world_map, dataset, left_on='name', right_on='name', how='left')
# Load a dataset with continent centroids from Natural Earth
continents = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# Plotting the map
fig, ax = plt.subplots(figsize=(12, 10))
# Specify the description for the colorbar
colorbar_description = "End Hunger - Food Security"
# Plot the map
merged_data.plot(ax=ax, column='goal_2_score', cmap='YlOrRd', linewidth=0.8, edgecolor='0.8', legend=False)
# Add label to the colorbar
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
# Plot the colorbar vertically on the right side
sm = plt.cm.ScalarMappable(cmap='YlOrRd', norm=plt.Normalize(vmin=merged_data['goal_2_score'].min(), vmax=merged_data['goal_2_score'].max()))
sm._A = []
cbar = plt.colorbar(sm, cax=cax)
# Add label to the colorbar
cbar.set_label(colorbar_description, rotation=270, labelpad=15, fontsize=12)
# Annotate continents only once
annotated_continents = set()
for idx, row in continents.iterrows():
continent_name = row['continent']
# Check if the continent has already been labeled
if continent_name not in annotated_continents:
centroid = row['geometry'].centroid
ax.annotate(text=continent_name, xy=(centroid.x, centroid.y),
xytext=(3, 3), textcoords="offset points", ha='center', fontsize=8)
annotated_continents.add(continent_name)
ax.set_title("Hunger in 2022", fontsize=16)
plt.savefig('/content/drive/MyDrive/hunger_map_2022.png', bbox_inches='tight')
plt.show()
dataset.head()
from mpl_toolkits.axes_grid1 import make_axes_locatable
# Assuming you have already loaded the world_map GeoDataFrame and the sdg_index_2000_2022 DataFrame
# If not, you should load them first
# Create the dataset based on the provided R code
dataset = sdg_index_2000_2022[sdg_index_2000_2022['year'] == 2022][['country', 'goal_1_score']]
dataset.columns = ['name', 'goal_1_score'] # Change 'country' to 'name' to match world_map
# Merge the GeoDataFrame and DataFrame on the 'name' column
merged_data = world_map.merge(dataset, left_on='name', right_on='name', how='left')
# Load a dataset with continent centroids from Natural Earth
continents = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# Plotting the map
fig, ax = plt.subplots(figsize=(12, 10))
# Specify the description for the colorbar
colorbar_description = "End Poverty In All Forms"
# Plot the map
merged_data.plot(ax=ax, column='goal_1_score', cmap='YlOrRd', linewidth=0.8, edgecolor='0.8', legend=False)
# Add label to the colorbar
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.1)
# Plot the colorbar vertically on the right side
sm = plt.cm.ScalarMappable(cmap='YlOrRd', norm=plt.Normalize(vmin=merged_data['goal_1_score'].min(), vmax=merged_data['goal_1_score'].max()))
sm._A = []
cbar = plt.colorbar(sm, cax=cax)
# Add label to the colorbar
cbar.set_label(colorbar_description, rotation=270, labelpad=15, fontsize=12)
# Annotate continents only once
annotated_continents = set()
for idx, row in continents.iterrows():
continent_name = row['continent']
# Check if the continent has already been labeled
if continent_name not in annotated_continents:
centroid = row['geometry'].centroid
ax.annotate(text=continent_name, xy=(centroid.x, centroid.y),
xytext=(3, 3), textcoords="offset points", ha='center', fontsize=8, color='orange') # Change color to white
annotated_continents.add(continent_name)
ax.set_title("Poverty in 2022", fontsize=16)
plt.savefig('/content/drive/MyDrive/poverty_map_2022.png', bbox_inches='tight')
plt.show()
# Select the column for the pie chart
selected_column = 'Density (per km虏)'
# Sort the DataFrame by the selected column
world_pop_sorted = world_pop.sort_values(by=selected_column, ascending=False).head(10)
# Plot a beautiful pie chart
fig, ax = plt.subplots(figsize=(10, 8))
# Define colors
colors = plt.cm.Paired(range(len(world_pop_sorted)))
# Plot the pie chart
ax.pie(world_pop_sorted[selected_column], labels=world_pop_sorted['Country/Territory'],
autopct='%1.1f%%', startangle=90, colors=colors)
# Set aspect ratio to be equal
ax.axis('equal')
# Set title
plt.title(f'Top 10 Countries by {selected_column}', fontsize=16)
# Show the pie chart
plt.show()
# Select the columns for the pie chart
years = ['2022 Population', '2020 Population', '2015 Population', '2010 Population', '2000 Population', '1990 Population', '1980 Population', '1970 Population']
# Sum the population for each year
population_sum = world_pop[years].sum()
# Plot a beautiful pie chart
fig, ax = plt.subplots(figsize=(10, 8))
# Define colors
colors = plt.cm.Paired(range(len(years)))
# Plot the pie chart
ax.pie(population_sum, labels=years, autopct='%1.1f%%', startangle=90, colors=colors)
# Set aspect ratio to be equal
ax.axis('equal')
# Set title
plt.title('Population Distribution for Each Year', fontsize=16)
# Show the pie chart
plt.show()
# Select the columns for the pie chart
years = ['2022 Population', '2020 Population', '2015 Population', '2010 Population', '2000 Population', '1990 Population', '1980 Population', '1970 Population']
# Sum the population for each year
population_sum = world_pop[years].sum()
# Plot a beautiful pie chart
fig, ax = plt.subplots(figsize=(10, 8))
# Define colors
colors = plt.cm.Paired(range(len(years)))
# Plot the pie chart
ax.pie(population_sum, labels=years, autopct='%1.1f%%', startangle=90, colors=colors)
# Set aspect ratio to be equal
ax.axis('equal')
# Set title
plt.title('World Population Distribution for Each Year', fontsize=16)
plt.savefig('/content/drive/MyDrive/world_population_each_year.png', bbox_inches='tight')
# Show the pie chart
plt.show()