<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 pprint as pp
import requests
import time
from citipy import citipy
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(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
    
    # 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># for x in range(len(indices)):
#     print(f"Making request number: {x} for ID: {indices[x]}")

#     # Get one of the posts
#     post_response = requests.get(url + str(indices[x]))

#     # Save post's JSON
#     response_json.append(post_response.json())

city_name = []
city_data = []
cloudiness = []
country = []
date = []
humidity = []
lat = []
lng = []
max_temp = []
wind_speed = []


# city_data = {"city_name" : [],
# "city_data : [],
# "cloudiness" : [],
# "country" : [],
# "date" : [],
# "humidity" : [],
# "lat" : [],
# "lng" : [],
# "max_temp" : [],
# "wind_speed" : []}

#query_url = url + city + "73911002d7a18b350355619e7799fdd8"
# query_url = "http://api.openweathermap.org/data/2.5/weather?q={city}&APPID=73911002d7a18b350355619e7799fdd8"

response = requests.get(query_url)

print("Beginning Data Retrieval")     
print("----------------------------")
record = 0

for city in cities:
    try:
        query_url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&APPID=73911002d7a18b350355619e7799fdd8"
        city_weather_info = requests.get(query_url).json()
#         lat = city_weather_info['coord']['lat']

#         city_data["city_name"].append(city_weather_info["name"])
#         city_data["cloudiness"].append(city_weather_info["clouds"])       
#         city_data["country"].append(city_weather_info["sys"]["country"])
#         city_data["date"].append(city_weather_info["dt"])
#         humidity.append(city_weather_info["main"]["humidity"])
#         lat.append(city_weather_info["coord"]["lat"])
#         lng.append(city_weather_info["coord"]["lon"])
#         max_temp.append(city_weather_info["main"]["temp_max"])
#         wind_speed.append(city_weather_info["wind"]["speed"])
#         city_record = city_weather_info["name"]
        
        # Append the City information into city_data list
        
        city_data.append({"City": city, 
                          "Lat": city_weather_info['coord']['lat'], 
                          "Lng": city_weather_info['coord']['lon'], 
                          "Max Temp": city_weather_info["main"]["temp_max"],
                          "Humidity": city_weather_info["main"]["humidity"],
                          "Cloudiness": city_weather_info["clouds"]["all"],
                          "Wind Speed": city_weather_info["wind"]["speed"],
                          "Country": city_weather_info["sys"]["country"],
                          "Date": city_weather_info["main"]["temp_max"]})
        
        time.sleep(1)
        print(f"Processing Record {record} | {city_record}")
        print(f"{query_url}&q={city}")
    except (TypeError, KeyError):
        print(f"Skipping {city}")

    record = record + 1
    
                          

city_weather_info
data = response.json()
data<jupyter_output><empty_output><jupyter_text>Convert Raw Data to DataFrame* Export the city data into a .csv.* Display the DataFrame<jupyter_code>city_data_df= pd.DataFrame(city_data,)

# lats = city_data_df["Lat"]
# max_temps = city_data_df["Max Temp"]
# humidity = city_data_df["Humidity"]
# cloudiness = city_data_df["Cloudiness"]
# wind_speed = city_data_df["Wind Speed"]

# Export the City_Data into a csv

city_data_df.to_csv(output_data_file, index_label="City_ID")
city_data_df.count()
city_data_df.head()<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># Build scatter plot for latitude vs. temperature
plt.scatter(lat, 
            max_temp,
            edgecolor="black", linewidths=1, marker="o", 
            alpha=0.8, label="Cities")

# Incorporate the other graph properties
plt.title("City Latitude vs. Max Temperature (%s)" % time.strftime("%x"))
plt.ylabel("Max Temperature (F)")
plt.xlabel("Latitude")
plt.grid(True)

# Save the figure
plt.savefig("output_data/Fig1.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Humidity Plot<jupyter_code>plt.scatter(lat, 
            humidity,
            edgecolor="black", linewidths=1, marker="o", 
            alpha=0.8, label="Cities")

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

# Save the figure
plt.savefig("output_data/Fig2.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Cloudiness Plot<jupyter_code># Build the scatter plots for latitude vs. cloudiness
plt.scatter(lat, 
            cloudiness,
            edgecolor="black", linewidths=1, marker="o", 
            alpha=0.8, label="Cities")

# Incorporate the other graph properties
plt.title("City Latitude vs. Cloudiness (%s)" % time.strftime("%x"))
plt.ylabel("Cloudiness (%)")
plt.xlabel("Latitude")
plt.grid(True)

# Save the figure
plt.savefig("output_data/Fig3.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Latitude vs. Wind Speed Plot<jupyter_code># Build the scatter plots for latitude vs. wind speed
plt.scatter(lat, 
            wind_speed,
            edgecolor="black", linewidths=1, marker="o", 
            alpha=0.8, label="Cities")

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

# Save the figure
plt.savefig("output_data/Fig4.png")

# Show plot
plt.show()<jupyter_output><empty_output><jupyter_text>Linear Regression<jupyter_code># OPTIONAL: Create a function to create Linear Regression plots

# Create a function to create Linear Regression plots
def plot_linear_regression(x_values, y_values, title, text_coordinates):
    
    # Run regresson on southern hemisphere
    (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))

    # Plot
    plt.scatter(x_values,y_values)
    plt.plot(x_values,regress_values,"r-")
    plt.annotate(line_eq,text_coordinates,fontsize=15,color="red")
    plt.xlabel('Latitude')
    plt.ylabel(title)
    print(f"The r-squared is: {rvalue}")
    plt.show()
# Create Northern and Southern Hemisphere DataFrames

northern_hemi_df = city_data_df.loc[(city_data_df["Lat"] >= 0)]
southern_hemi_df = city_data_df.loc[(city_data_df["Lat"] < 0)]<jupyter_output><empty_output><jupyter_text>Northern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code># Linear regression on Northern Hemisphere
x_values = northern_hemi_df["Lat"]
y_values = northern_hemi_df["Max Temp"]
plot_linear_regression(x_values, y_values, 'Max Temp',(6,30))<jupyter_output>The r-squared is: -0.8882298448471247<jupyter_text>Southern Hemisphere - Max Temp vs. Latitude Linear Regression<jupyter_code>x_values = southern_hemi_df["Lat"]
y_values = southern_hemi_df["Max Temp"]
plot_linear_regression(x_values, y_values, 'Max Temp', (-30,40))<jupyter_output>The r-squared is: 0.4313352880757277<jupyter_text>Northern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code># Northern Hemisphere
x_values = northern_hemi_df["Lat"]
y_values = northern_hemi_df["Humidity"]
plot_linear_regression(x_values, y_values, 'Humidity',(40,10))<jupyter_output>The r-squared is: 0.37958700229754555<jupyter_text>Southern Hemisphere - Humidity (%) vs. Latitude Linear Regression<jupyter_code># Southern Hemisphere
x_values = southern_hemi_df["Lat"]
y_values = southern_hemi_df["Humidity"]
plot_linear_regression(x_values, y_values, 'Humidity', (-30,150))<jupyter_output>The r-squared is: 0.13061547577476204<jupyter_text>Northern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code># Northern Hemisphere
x_values = northern_hemi_df["Lat"]
y_values = northern_hemi_df["Cloudiness"]
plot_linear_regression(x_values, y_values, 'Cloudiness', (40,10))<jupyter_output>The r-squared is: -0.08733547918934018<jupyter_text>Southern Hemisphere - Cloudiness (%) vs. Latitude Linear Regression<jupyter_code># Southern Hemisphere
x_values = southern_hemi_df["Lat"]
y_values = southern_hemi_df["Cloudiness"]
plot_linear_regression(x_values, y_values, 'Cloudiness', (-30,30))<jupyter_output>The r-squared is: 0.21881426893991618<jupyter_text>Northern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code># Northern Hemisphere
x_values = northern_hemi_df["Lat"]
y_values = northern_hemi_df["Wind Speed"]
plot_linear_regression(x_values, y_values, 'Wind Speed', (40,25))<jupyter_output>The r-squared is: 0.08335586767386548<jupyter_text>Southern Hemisphere - Wind Speed (mph) vs. Latitude Linear Regression<jupyter_code># Southern Hemisphere
x_values = southern_hemi_df["Lat"]
y_values = southern_hemi_df["Wind Speed"]
plot_linear_regression(x_values, y_values, 'Wind Speed', (-30,30))<jupyter_output>The r-squared is: -0.261050094118375
{'fraction_non_alphanumeric': 0.13143555054490794, 'fraction_numerical': 0.02987598647125141, 'mean_word_length': 4.6233491811938725, 'pattern_counts': {'":': 9, '<': 62, '<?xml version=': 0, '>': 62, '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': '512198', 'license': 'MIT', 'n_tokens_mistral': 3959, 'n_tokens_neox': 3637, 'n_words': 774, 'path': 'WeatherPY/.ipynb_checkpoints/WeatherPY-checkpoint.ipynb', 'repo_name': 'Davidtaboh/WeatherPy', 'size': '10644'}