Advertisement
Guest User

Untitled

a guest
Jun 10th, 2025
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.39 KB | None | 0 0
  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import os
  4. import numpy as np
  5. from tkinter import Tk, Label, Listbox, Button, MULTIPLE, Frame, StringVar, messagebox
  6.  
  7. def load_data_and_plot():
  8.     # Get the current directory where the script is located
  9.     current_dir = os.path.dirname(os.path.abspath(__file__))
  10.  
  11.     # Load the CO2 emissions data
  12.     emissions_file = os.path.join(current_dir, 'annual-co2-emissions-per-country.csv')
  13.     emissions_data = pd.read_csv(emissions_file)
  14.  
  15.     # Load the population data
  16.     population_file = os.path.join(current_dir, 'population.csv')
  17.     population_data = pd.read_csv(population_file)
  18.  
  19.     # Create GUI for entity selection
  20.     root = Tk()
  21.     root.title("CO2 Emissions Per Capita Plotter")
  22.     root.geometry("500x400")
  23.  
  24.     # Get all unique entities (countries)
  25.     all_entities = sorted(list(set(emissions_data['Entity']) & set(population_data['Entity'])))
  26.  
  27.     # Frame for entity selection
  28.     selection_frame = Frame(root)
  29.     selection_frame.pack(pady=10, fill="both", expand=True)
  30.  
  31.     Label(selection_frame, text="Select countries to plot:", font=("Arial", 12)).pack(pady=5)
  32.  
  33.     # Create listbox for entity selection
  34.     entity_listbox = Listbox(selection_frame, selectmode=MULTIPLE, height=15, width=40)
  35.     entity_listbox.pack(fill="both", expand=True, padx=20, pady=5)
  36.  
  37.     # Add entities to listbox
  38.     for entity in all_entities:
  39.         entity_listbox.insert('end', entity)
  40.  
  41.     # Button frame
  42.     button_frame = Frame(root)
  43.     button_frame.pack(pady=10)
  44.  
  45.     # Function to plot selected entities
  46.     def plot_selected_entities():
  47.         # Get selected indices
  48.         selected_indices = entity_listbox.curselection()
  49.        
  50.         if not selected_indices:
  51.             messagebox.showwarning("Warning", "No countries selected. Please select at least one country.")
  52.             return
  53.        
  54.         # Get selected entity names
  55.         selected_entities = [entity_listbox.get(i) for i in selected_indices]
  56.        
  57.         # Colors for different entities
  58.         colors = ['#004488', '#BB5566', '#DDAA33', '#009988', '#EE3377', '#44BB99', '#AA3377', '#882255']
  59.  
  60.         # Create plot
  61.         plt.figure(figsize=(14, 7))
  62.        
  63.         # For legend
  64.         plot_handles = []
  65.         plot_labels = []
  66.        
  67.         # Min and max years for consistent x-axis
  68.         min_year = 2023
  69.         max_year = 1950
  70.        
  71.         # For y-axis scaling
  72.         max_value = 0
  73.        
  74.         # Plot each selected entity with a different color
  75.         for i, entity in enumerate(selected_entities):
  76.             color_idx = i % len(colors)  # Cycle through colors if more entities than colors
  77.            
  78.             # Filter data for the entity
  79.             entity_emissions = emissions_data[emissions_data['Entity'] == entity]
  80.             entity_population = population_data[population_data['Entity'] == entity]
  81.            
  82.             # Filter for years from 1950 onwards
  83.             entity_emissions_filtered = entity_emissions[entity_emissions['Year'] >= 1950]
  84.             entity_population_filtered = entity_population[entity_population['Year'] >= 1950]
  85.            
  86.             # Merge the datasets on 'Year'
  87.             merged_data = pd.merge(entity_emissions_filtered, entity_population_filtered, on='Year')
  88.            
  89.             if merged_data.empty:
  90.                 messagebox.showinfo("Info", f"No data found for {entity} after 1950")
  91.                 continue
  92.                
  93.             # Update min/max year for x-axis limits
  94.             if merged_data['Year'].min() < min_year:
  95.                 min_year = merged_data['Year'].min()
  96.             if merged_data['Year'].max() > max_year:
  97.                 max_year = merged_data['Year'].max()
  98.            
  99.             # Get column names
  100.             emissions_col = [col for col in merged_data.columns if 'CO2' in col or 'emissions' in col.lower()][0]
  101.             population_col = 'all years'  # Column name for population
  102.            
  103.             # Calculate per capita emissions (tons of CO2 per person)
  104.             merged_data['CO2_per_capita'] = merged_data[emissions_col] / merged_data[population_col]
  105.            
  106.             # Update max value for y-axis scaling
  107.             if merged_data['CO2_per_capita'].max() > max_value:
  108.                 max_value = merged_data['CO2_per_capita'].max()
  109.            
  110.             # Plot the data
  111.             line, = plt.plot(merged_data['Year'], merged_data['CO2_per_capita'],
  112.                           marker='o', linestyle='-', color=colors[color_idx], linewidth=2,
  113.                           label=entity)
  114.            
  115.             plot_handles.append(line)
  116.             plot_labels.append(entity)
  117.            
  118.             # Add annotation for peak value
  119.             max_year_entity = merged_data.loc[merged_data['CO2_per_capita'].idxmax(), 'Year']
  120.             max_value_entity = merged_data['CO2_per_capita'].max()
  121.            
  122.             plt.annotate(f'{entity} peak: {max_value_entity:.2f}',
  123.                          xy=(max_year_entity, max_value_entity),
  124.                          xytext=(max_year_entity+2, max_value_entity+0.3),
  125.                          arrowprops=dict(arrowstyle='->', color=colors[color_idx]))
  126.        
  127.         # Add title and labels
  128.         plt.title('CO2 Emissions Per Capita (1950-Present)', fontsize=16)
  129.         plt.xlabel('Year', fontsize=12)
  130.         plt.ylabel('CO2 Emissions (tons per person)', fontsize=12)
  131.         plt.grid(True, alpha=0.3)
  132.        
  133.         # Set axis limits
  134.         plt.xlim(min_year-1, max_year+1)
  135.         plt.ylim(0, max_value * 1.15)  # Add 15% padding at the top
  136.        
  137.         # Add legend
  138.         plt.legend(handles=plot_handles, labels=plot_labels, loc='best')
  139.        
  140.         # Improve formatting
  141.         plt.tight_layout()
  142.        
  143.         # Save the figure
  144.         save_path = os.path.join(current_dir, 'co2_per_capita_comparison.png')
  145.         plt.savefig(save_path, dpi=300)
  146.        
  147.         # Show the plot
  148.         plt.show()
  149.        
  150.         print(f"Plot created and saved as 'co2_per_capita_comparison.png'")
  151.        
  152.         # Close the GUI
  153.         root.destroy()
  154.  
  155.     # Plot button
  156.     Button(button_frame, text="Plot Selected Countries", command=plot_selected_entities,
  157.            font=("Arial", 12), bg="#4CAF50", fg="white", padx=10).pack(pady=5)
  158.  
  159.     # Run the GUI
  160.     root.mainloop()
  161.  
  162. if __name__ == "__main__":
  163.     load_data_and_plot()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement