<jupyter_start><jupyter_text>WeatherPy---- Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps. Intro:In this project for WeatherPy, we used both a Weather API key and Google API key to make calls to gather city weather related information.We gathered data for key measures such as Max Temperature, Humidity, location compared to the equator, Cloudiness, and Wind Speed.According to BBC, there are other environmental factors that can affect the temperature of a specific location such as Altitude and distance from the sea. But like any Research Project, there are limitations.  (citation, https://www.bbc.co.uk/bitesize/guides/zgyw4qt/revision/2)From this information, I was able to draw some conclusions by running Scatter plots and Linear Regression against various variables.Key finding:*1. There is a strong negative correlation of -.70 when comparing the Northern Hemisphere's Max Temp vs  Latitude. Concluding the temperature drops the further North of the  Equator (Lat=0) you go.*2. Vice Versa, there is a positive correlation of .77 when comparing the Southern Hemisphere's Max Temperature vs Latitude. Thus, supporting the same above conclusion, the  further away you go from the Equator the lower the temperature gets.*3. Surprisingly, there was no real correlation between the Northern/Southern Hemisphere Cloudiness vs Latitude with Linear Regressions of (-.02, -.1), retrospectively. I was under the impression that the higher the temperature by the Equator the less shade there would be, but this data proved me wrong.As Global Warming becomes a bigger concern, it would be interesting to have compared Max Temperature from 50 years ago to add some trending to this project. We are seeing Gen Z and Millennials are more concerned about environmental conservation than previous generations . Making these findings very relevant to today's continous topic of conversation on Global Warming.You will find my code and graphs below.<jupyter_code># Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import datetime
import time
import scipy.stats as st
from scipy.stats import linregress

# Import API key
from api_keys import weather_api_key

# Incorporated citipy to determine city based on latitude and longitude
from citipy import citipy

# Output File (CSV)
output_data_file = "output_data/cities.csv"

# Range of latitudes and longitudes
lat_range = (-90, 90)
lng_range = (-180, 180)<jupyter_output><empty_output><jupyter_text>Generate Cities List<jupyter_code># List for holding lat_lngs and cities
lat_lngs = []
cities = []

# Create a set of random lat and lng combinations
lats = np.random.uniform(lat_range[0], lat_range[1], size=1500)
lngs = np.random.uniform(lng_range[0], lng_range[1], size=1500)
lat_lngs = zip(lats, lngs)

# Identify nearest city for each lat, lng combination
for lat_lng in lat_lngs:
    city = citipy.nearest_city(lat_lng[0], lat_lng[1]).city_name
    
    # If the city is unique, then add it to a our cities list
    if city not in cities:
        cities.append(city)

# Print the city count to confirm sufficient count
len(cities)<jupyter_output><empty_output><jupyter_text>Perform API Calls* Perform a weather check on each city using a series of successive API calls.* Include a print log of each city as it'sbeing processed (with the city number and city name).<jupyter_code>#create counters for print
record_count= 1
set_count= 1 
city_data= []

for i, city in enumerate(cities):
    if (i % 50 == 0 and i >= 50):
        set_count += 1
        record_count= 0
   
    print("Processing Record %s of set %s | %s" %(record_count, set_count, city))
    
    #reset the index
    record_count += 1
    
    #give the API web address
    url = f'http://api.openweathermap.org/data/2.5/weather?q={city}&appid={weather_api_key}'
    #print(url)
    
    try:
        response = requests.get(url).json()
        temp = response['main']['temp']
        lat = response['coord']['lat']
        lon = response['coord']['lon']
        country = response['sys']['country']
        date = response['dt']
        city_max_temp = response['main']['temp_max']
        city_humidity = response['main']['humidity']
        wind_speed = response['wind']['speed']
        clouds = response['clouds']['all']
        
        #Append city into city_info
        city_data.append({"City": city,
                      "Temperature" : city_max_temp,
                      "Humidity" : city_humidity,
                      "Longitude" : lon,
                      "Latitude" : lat,
                      "Cloudiness" : clouds,
                      "Country" : country,
                      "Windspeed" : wind_speed,
                      "Date" : date
                      })
        
    except:
        print("City not found. Skipping...")
        pass
        
print("------------")
print("Data Retrieval Complete")
print("------------")<jupyter_output>Processing Record 1 of set 1 | lincoln
Processing Record 2 of set 1 | ushuaia
Processing Record 3 of set 1 | smoky lake
Processing Record 4 of set 1 | kindu
Processing Record 5 of set 1 | moranbah
Processing Record 6 of set 1 | mataura
Processing Record 7 of set 1 | hobart
Processing Record 8 of set 1 | sechura
Processing Record 9 of set 1 | albany
Processing Record 10 of set 1 | berlevag
Processing Record 11 of set 1 | bambous virieux
Processing Record 12 of set 1 | buluang
Processing Record 13 of set 1 | saint-philippe
Processing Record 14 of set 1 | avarua
Processing Record 15 of set 1 | puerto ayora
Processing Record 16 of set 1 | barrow
Processing Record 17 of set 1 | hailey
Processing Record 18 of set 1 | tasiilaq
Processing Record 19 of set 1 | busselton
Processing Record 20 of set 1 | nikel
Processing Record 21 of set 1 | cidreira
Processing Record 22 of set 1 | maromitsa
Processing Record 23 of set 1 | carnarvon
Processing Record 24 of set 1 | port hueneme
Processing Record 25[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>city_weather_data_pd= pd.DataFrame(city_data)
city_weather_data_pd<jupyter_output><empty_output><jupyter_text>Plotting the Data* Use proper labeling of the plots using plot titles (including date of analysis) and axes labels.* Save the plotted figures as .pngs.  Latitude vs. Temperature Plot<jupyter_code>#today's date
date= datetime.date.today()
date=time.strftime("%m/%d/%Y")

# Build a scatter plot for each data type
plt.scatter(city_weather_data_pd['Latitude'], city_weather_data_pd['Temperature'], edgecolor="black", linewidths=1, marker="o", alpha=0.8, label="cities")

# Incorporate the other graph properties
plt.title(f"Latitude vs Temperature {date}", fontsize="14")
plt.ylabel("Temperature (F)", fontsize="12")
plt.xlabel("Latitude", fontsize="12")
plt.grid(True)

# Save the figure
plt.savefig("Temperature.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code>#today's date
date= datetime.date.today()
date=time.strftime("%m/%d/%Y")

# Build a scatter plot for each data type
plt.scatter(city_weather_data_pd['Latitude'], city_weather_data_pd['Humidity'], edgecolor="black", linewidths=1, marker="o", alpha=0.8, label="cities")

# Incorporate the other graph properties
plt.title(f"Latitude vs Humidity {date}", fontsize="14")
plt.ylabel("Humidity (%)", fontsize="12")
plt.xlabel("Latitude", fontsize="12")
plt.grid(True)

# Save the figure
plt.savefig("Humidity.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code>#today's date
date= datetime.date.today()
date=time.strftime("%m/%d/%Y")

# Build a scatter plot for each data type
plt.scatter(city_weather_data_pd['Latitude'], city_weather_data_pd['Cloudiness'], edgecolor="black", linewidths=1, marker="o", alpha=0.8, label="cities")

# Incorporate the other graph properties
plt.title(f"Latitude vs Cloudiness {date}", fontsize="14")
plt.ylabel("Cloudiness", fontsize="12")
plt.xlabel("Latitude", fontsize="12")
plt.grid(True)

# Save the figure
plt.savefig("Cloudiness.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code>#today's date
date= datetime.date.today()
date=time.strftime("%m/%d/%Y")

# Build a scatter plot for each data type
plt.scatter(city_weather_data_pd['Latitude'], city_weather_data_pd['Windspeed'], edgecolor="black", linewidths=1, marker="o", alpha=0.8, label="cities")

# Incorporate the other graph properties
plt.title(f"Latitude vs Windspeed {date}", fontsize="14")
plt.ylabel("Windspeed (mph)", fontsize="12")
plt.xlabel("Latitude", fontsize="12")
plt.grid(True)

# Save the figure
plt.savefig("Wind_speed.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># OPTIONAL: Create a function to create Linear Regression plots
def linear_agression(x,y):
    print(f"The r-squared is : {round(st.pearsonr(x,y)[0],2)}")
    (slope, intercept, rvalue, pvalue, stderr) = linregress(x,y)
    regress_values = x * slope + intercept
    line_equation = "y =" + str(round(slope,2)) + "x +" + str(round(intercept,2))
    plt.scatter(x,y)
    plt.plot(x,regress_values, "r-")
    return line_equation

#add annotations
def annotate(line_equation, a,b):
    plt.annotate(line_equation,(a,b), fontsize=12, color="red")
# Create Northern and Southern Hemisphere DataFrames
#locate northern hem
northern_hem_df=city_weather_data_pd.loc[city_weather_data_pd['Latitude'] >= 0]

#locate southern hem
southern_hem_df=city_weather_data_pd.loc[city_weather_data_pd['Latitude'] < 0 ]<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on temperature vs. latitude

equation= linear_agression(northern_hem_df["Latitude"], northern_hem_df["Temperature"])
plt.title("Northern Hemisphere - Max Temp vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Max Temp (F)")
annotate(equation,0,280)

plt.savefig("Northern Hemisphere - Max Temp vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : -0.72<jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on temperature vs. latitude

equation= linear_agression(southern_hem_df["Latitude"], southern_hem_df["Temperature"])
plt.title("Southern Hemisphere - Max Temp vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Max Temp (F)")
annotate(equation,-20,275)

plt.savefig("Southern Hemisphere - Max Temp vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : 0.77<jupyter_text>Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on Humidity vs. latitude

equation= linear_agression(northern_hem_df["Latitude"], northern_hem_df["Humidity"])
plt.title("Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
annotate(equation,50,20)

plt.savefig("Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : 0.03<jupyter_text>Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on Humidity vs. latitude

equation= linear_agression(southern_hem_df["Latitude"], southern_hem_df["Humidity"])
plt.title("Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Humidity (%)")
annotate(equation,-55,40)

plt.savefig("Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : -0.14<jupyter_text>Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on Cloudiness vs. latitude

equation= linear_agression(northern_hem_df["Latitude"], northern_hem_df["Cloudiness"])
plt.title("Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
annotate(equation,20,55)

plt.savefig("Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : -0.02<jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on Cloudiness vs. latitude

equation= linear_agression(southern_hem_df["Latitude"], southern_hem_df["Cloudiness"])
plt.title("Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Cloudiness (%)")
annotate(equation,-55,10)

plt.savefig("Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : -0.1<jupyter_text>Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on Wind Speend vs. latitude

equation= linear_agression(northern_hem_df["Latitude"], northern_hem_df["Windspeed"])
plt.title("Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
annotate(equation,40,10)

plt.savefig("Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : -0.09<jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code># Perform a linear regression on Cloudiness vs. latitude

equation= linear_agression(southern_hem_df["Latitude"], southern_hem_df["Windspeed"])
plt.title("Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression")
plt.xlabel("Latitude")
plt.ylabel("Wind Speed (mph)")
annotate(equation,-57,4)

plt.savefig("Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression.png")<jupyter_output>The r-squared is : -0.05
{'fraction_non_alphanumeric': 0.10861611306406485, 'fraction_numerical': 0.015424348948992037, 'mean_word_length': 5.029411764705882, 'pattern_counts': {'":': 1, '<': 61, '<?xml version=': 0, '>': 62, 'https://': 1, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '17', 'dir': 'jupyter-structured-clean-dedup', 'id': '131273', 'license': 'ADSL', 'n_tokens_mistral': 4720, 'n_tokens_neox': 4262, 'n_words': 1352, 'path': 'starter_code/WeatherPy.ipynb', 'repo_name': 'Aschaefer152/python-api-challenge3', 'size': '13939'}