<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.<jupyter_code>#Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import requests
import time
from scipy.stats import linregress

# Import API key
from api_keys import 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(low=-90.000, high=90.000, size=1500)
lngs = np.random.uniform(low=-180.000, high=180.000, 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
    city = city.replace(" ", "%20")
    # 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>#Name url and extract data
url = f"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q={city}&units=Imperial"
url
#Create empty lists for for loop
city_name = []
cloudiness = []
country = []
date = []
humidity = []
lat = []
lng = []
maxTemp = []
windSpeed = []

record = 1

#creat a for loop that loops through data. Also creat try and except statement and append response/url data.

for city in cities:
    url = f"http://api.openweathermap.org/data/2.5/weather?appid={api_key}&q={city}&units=Imperial"
    try:
        response = requests.get(url).json()
        city_name.append(response["name"])
        cloudiness.append(response["clouds"]["all"])
        country.append(response["sys"]["country"])
        date.append(response["dt"])
        humidity.append(response["main"]["humidity"])
        lat.append(response["coord"]["lat"])
        lng.append(response["coord"]["lon"])
        maxTemp.append(response["main"]["temp"])
        windSpeed.append(response["wind"]["speed"])
        cityRecord = response["name"]
        print(f"Processing Record {record} | {cityRecord}")
        
        #Create a time function that will prevent you from being blocked for running the api too often.
        record= record + 1
        time.sleep(1.01)
    except:
        print("No City")
        print(response)
#g_key
#Printed out cities to make sure there were multiple cities.
print(cities)<jupyter_output>['sao%20filipe', 'puerto%20ayora', 'preeceville', 'san%20isidro', 'punta%20arenas', 'mahebourg', 'avarua', 'chuy', 'cape%20town', 'bluff', 'port%20elizabeth', 'mackay', 'yellowknife', 'vao', 'atuona', 'sitka', 'novouzensk', 'bihoro', 'lata', 'guaruja', 'mys%20shmidta', 'hermanus', 'jamestown', 'cururupu', 'altay', 'ulcinj', 'ushuaia', 'shingu', 'uvira', 'riyadh', 'hobart', 'umm%20kaddadah', 'bilma', 'bandarbeyla', 'taolanaro', 'acapulco', 'pacific%20grove', 'zhigansk', 'fortuna', 'new%20norfolk', 'arraial%20do%20cabo', 'le%20portel', 'sinnamary', 'kapaa', 'sentyabrskiy', 'butaritari', 'amderma', 'clyde%20river', 'kloulklubed', 'port%20alfred', 'gat', 'san%20juan%20de%20uraba', 'victoria', 'cayenne', 'turbat', 'barrow', 'japura', 'nurmijarvi', 'tasiilaq', 'kenai', 'cap%20malheureux', 'townsville', 'guerrero%20negro', 'quijingue', 'lagoa', 'albany', 'rikitea', 'luanda', 'grand%20river%20south%20east', 'ihosy', 'rawson', 'udachnyy', 'bathsheba', 'mataura', 'zharkent', 'cherskiy', 'hithadh[...]<jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>#Create a dictionary with all columns inside for data frame.
weatherDict = {
    "City": city_name,
    "Cloudiness":cloudiness, 
    "Country":country,
    "Date":date, 
    "Humidity": humidity,
    "Lat":lat, 
    "Lng":lng, 
    "Max Temp": maxTemp,
    "Wind Speed":windSpeed
}
weatherData = pd.DataFrame(weatherDict)
weatherData<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.<jupyter_code>#Create a scatter plot that shows Latitude vs Temperature.
plt.scatter(weatherData["Lat"], weatherData["Max Temp"], marker="o", s=10)

#Include other graph data
plt.title("Latitude vs. Temperature")
plt.ylabel("Max. Temperature (F)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Temperature Plot  Latitude vs. Humidity Plot<jupyter_code># Build a scatter plot for Latitude vs Humidity
plt.scatter(weatherData["Lat"], weatherData["Humidity"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("City Latitude vs. Humidity")
plt.ylabel("Humidity (%)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code># Build a scatter plot for Latitude vs Cloudiness

plt.scatter(weatherData["Lat"], weatherData["Cloudiness"], marker="o", s=10)
# Incorporate the other graph properties
plt.title("City Latitude vs. Cloudiness")
plt.ylabel("Cloudiness (%)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code># Build a scatter plot for Latitude vs Wind Speed
plt.scatter(weatherData["Lat"], weatherData["Wind Speed"], marker="o", s=10)

# Incorporate the other graph properties
plt.title("City Latitude vs. Wind Speed")
plt.ylabel("Wind Speed (mph)")
plt.xlabel("Latitude")
plt.grid(True)

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># OPTIONAL: Create a function to create Linear Regression plots
# That way you can call your function once.
def plotLinReg(x_values, y_values, label):
    (slope, intercept, rvalue, pvalue, stderr) = linregress(x_values, y_values)
    regress_values = x_values * slope + intercept
    line_eq = "y = " + str(round(slope,2)) + "x + " + str(round(intercept,2))
    plt.scatter(x_values,y_values)
    plt.plot(x_values,regress_values,"r-")
    plt.annotate(line_eq,(6,10),fontsize=15,color="red")
    plt.xlabel(label)
    plt.ylabel('Latitude')
    print(f"The r-squared is: {rvalue}")
    plt.show()
# Create Northern and Southern Hemisphere DataFrames
#Create a northern hem Data Frame with appropriate columns
cityDataNorth = weatherData[weatherData["Lat"] > 0]


cloudinessNorth = cityDataNorth["Cloudiness"]
humidityNorth = cityDataNorth["Humidity"]
latitudeNorth = cityDataNorth["Lat"]
maxTempNorth = cityDataNorth["Max Temp"]
windSpeedNorth = cityDataNorth["Wind Speed"]

#Create a southern hem Data Frame with appropriate columns
cityDataSouth = weatherData[weatherData["Lat"] < 0]

cloudinessSouth = cityDataSouth["Cloudiness"]
humiditySouth = cityDataSouth["Humidity"]
latitudeSouth = cityDataSouth["Lat"]
maxTempSouth = cityDataSouth["Max Temp"]
windSpeedSouth = cityDataSouth["Wind Speed"]<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>#Create a linear regression that correlates the latitude(distance from sun) to the decrease in temperature. Repeat  this step for all other graphs.
x_values = maxTempNorth
y_values = latitudeNorth
label = "Max Temp"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: -0.8758551114116537<jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>x_values = maxTempSouth
y_values = latitudeSouth
label = "Max Temp"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: 0.4740819196202261<jupyter_text>Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>x_values = humidityNorth
y_values = latitudeNorth
label = "Humidity"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: 0.34180516835097974<jupyter_text>Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code>x_values = humiditySouth
y_values = latitudeSouth
label = "Humidity"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: 0.36104568202359677<jupyter_text>Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>x_values = cloudinessNorth
y_values = latitudeNorth
label = "Cloudiness"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: 0.2326725510610712<jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code>x_values = cloudinessSouth
y_values = latitudeSouth
label = "Cloudiness"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: 0.2161457531459882<jupyter_text>Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>x_values = windSpeedNorth
y_values = latitudeNorth
label = "Wind Speed"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: 0.07054617623836028<jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code>x_values = windSpeedSouth
y_values = latitudeSouth
label = "Wind Speed"
plotLinReg(x_values, y_values, label)<jupyter_output>The r-squared is: -0.3100159476114837
{'fraction_non_alphanumeric': 0.12610030706243602, 'fraction_numerical': 0.026100307062436028, 'mean_word_length': 5.9445628997867805, 'pattern_counts': {'":': 9, '<': 61, '<?xml version=': 0, '>': 61, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '651276', 'license': 'ADSL', 'n_tokens_mistral': 3619, 'n_tokens_neox': 3296, 'n_words': 838, 'path': 'starter_code/WeatherPy.ipynb', 'repo_name': 'agordongrad/project-api-challenge', 'size': '9770'}