import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
import seaborn as sns
import mysql.connector
def connect_to_database(host_name, user_name, user_password, user_database):
connection = None
Error = None
try:
connection = mysql.connector.connect(
host = host_name,
user = user_name,
passwd = user_password,
database = user_database
)
return connection
except Error as e:
print(f"The error '{e}' occurred")
def execute_query(connection, query):
cursor = connection.cursor()
result = None
Error = None
try:
cursor.execute(query)
result = cursor.fetchall()
return result
except Error as e:
print(f"The error '{e}' occurred")
connection = connect_to_database("localhost", "root", "", "meteo")
query = "SELECT year, ann, spring, summer, autumn, winter from temp_mean"
result = execute_query(connection, query)
mean = pd.DataFrame(result, columns = ['year', 'ann', 'spring', 'summer', 'autumn', 'winter'])
mean['year'] = mean['year'].astype(float) # We need to convert these to floats for some of
mean['ann'] = mean['ann'].astype(float) # the maths we are going to perform on them
mean['spring'] = mean['spring'].astype(float)
mean['summer'] = mean['summer'].astype(float)
mean['autumn'] = mean['autumn'].astype(float)
mean['winter'] = mean['winter'].astype(float)
mean = mean.iloc[: -1, :] # The data for 2023 is incomplete, so delete it
x = mean["year"]
y = mean["ann"]
plt.xlabel('x-axis', fontsize=10)
plt.ylabel('y-axis', fontsize=10)
plt.title('UK Mean Annual Temperatures')
plt.xlabel('Years')
plt.ylabel('Temperature')
plt.plot(x, y, lw=0.5, color='b') # Print Plot
plt.savefig("Temp.jpg") # Save Plot as jpg
x = mean["year"]
y = mean["ann"]
plt.title('UK Mean Annual Temperature Trend')
plt.xlabel('Years')
plt.ylabel('Temperature')
plt.scatter(x, y, s=5) # Print scatterplot
z = np.polyfit(x, y, 1) # Calculate equation for Trend line
p = np.poly1d(z)
plt.plot(x, p(x), color='r') # add trendline to plot
z = np.polyfit(x, y, 3) # Calculate equation for Trend line
p = np.poly1d(z)
plt.plot(x, p(x), color='g') # add trendline to plot
plt.gca().legend(('Temp','1 Deg', '3 Deg'), loc = 'lower right')
plt.savefig("Temp_Trend.jpg") # Save Plot as jpg
query = "SELECT year, ann from rain"
result = execute_query(connection, query)
rain = pd.DataFrame(result, columns = ['year', 'ann'])
rain['year'] = rain['year'].astype(float) # We need to convert these to floats for some of
rain['ann'] = rain['ann'].astype(float) # the maths we are going to perform on them
rain = rain.iloc[: -1, :] # The data for 2023 is incomplete, so delete it
x = rain["year"]
y = rain["ann"]
plt.xlabel('x-axis', fontsize=10)
plt.ylabel('y-axis', fontsize=10)
plt.title('UK Average Annual Rainfall')
plt.xlabel('Years')
plt.ylabel('Rainfall (mm)')
plt.plot(x, y, lw=0.5, color='b') # Print Plot
plt.savefig("Rainfall.jpg") # Save Plot as jpg
x = rain["year"]
y = rain["ann"]
plt.title('UK Mean Annual Rainfall Trend')
plt.xlabel('Years')
plt.ylabel('Rainfall')
plt.scatter(x, y, s=5) # Print scatterplot
z = np.polyfit(x, y, 1) # Calculate equation for Trend line
p = np.poly1d(z)
plt.plot(x, p(x), color='r') # add trendline to plot
z = np.polyfit(x, y, 3) # Calculate equation for Trend line
p = np.poly1d(z)
plt.plot(x, p(x), color='g') # add trendline to plot
plt.gca().legend(('Rainfall','1 Deg', '3 Deg'), loc = 'lower right')
plt.savefig("Temp_Trend.jpg") # Save Plot as jpg
## Plot Mean Temperature for each Decade
decades = ['1900', '1910', '1920', '1930', '1940', '1950', '1960', '1970', '1980', '1990', '2000', '2010']
dec_temps = pd.Series()
for x in decades:
x = x[0:3] + '%'
query = """SELECT sum(ann) as Total from temp_mean where year like '{}';""".format(x)
result = execute_query(connection, query)
for row in result:
temp = row[0]
dec_temps.loc[x] = temp/10
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.bar(decades,dec_temps, color = 'lightblue')
ax.set(ylabel='Temperature', xlabel='Years', title='Mean Temperature per Decade', ylim=(7.5, 9.5))
plt.savefig("Av_Decade_temp.jpg", bbox_inches='tight') # Save Plot as jpg
plt.show()
## Plot Mean Temperauter for each Decade showing Min and Max Mean Annual Temperatures for each Decade
decades = ['1900', '1910', '1920', '1930', '1940', '1950', '1960', '1970', '1980', '1990', '2000', '2010']
temperatures = {
'Min' : np.array([7.52, 7.42, 7.63, 7.98, 7.96, 7.90, 7.40, 7.59, 7.67, 8.18, 8.80, 7.94]),
'Mean': np.array([0.50, 0.74, 0.63, 0.51, 0.57, 0.49, 0.72, 0.77, 0.71, 0.73, 0.51, 1.24]),
'Max' : np.array([0.29, 0.65, 0.98, 0.43, 0.81, 0.85, 0.55, 0.41, 0.85, 0.50, 0.39, 0.70]),
}
width = 0.6 # the width of the bars: can also be len(x) sequence
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
bottom = np.zeros(12)
colors = ['lightblue', 'lavender', 'orange']
print (colors[0])
i = 0
for temp, temps in temperatures.items():
p = ax.bar(decades, temps, width=0.9, label=temp, bottom=bottom, color = colors[i])
bottom += temps
i= i+1
# ax.bar_label(p, label_type='center')
ax.set(ylabel='Temperature', xlabel='Years', title='Mean Decade Temperatures Showing Min & Max', ylim=(7.0, 10.0))
ax.legend()
plt.savefig("min_max.jpg", bbox_inches='tight') # Save Plot as jpg
plt.show()
lightblue
## Plot Temperature Against Rainfall
import numpy as np
import matplotlib.pyplot as plt
# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
x = mean["year"]
y = mean["ann"]
data1 = y
data2 = x
fig, ax1 = plt.subplots()
color = 'tab:red'
ax1.set_title('Temp v Rainfall')
ax1.set_xlabel('Years')
ax1.set_ylabel('Temperature', color=color)
ax1.plot(x, data1, lw=0.5, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
y = rain["ann"]
data3 = y
color = 'tab:blue'
ax2.set_ylabel('Rainfall', color=color) # we already handled the x-label with ax1
ax2.plot(x, data3, lw=0.5, color=color)
ax2.tick_params(axis='y', labelcolor=color)
#fig.tight_layout() # otherwise the right y-label is slightly clipped
plt.savefig("rain_temp.jpg", bbox_inches='tight')
plt.show()
## Plot the Mean Temperatures for each Season
years = mean["year"]
plt.title('UK Mean Seasonal Temperatures per Decade')
plt.xlabel('Years')
plt.ylabel('Temperature')
colors = ['green', 'red', 'orange', 'blue']
line_1 = plt.plot(years, mean['spring'], lw=0.5, color=colors[0], label="Spring") # Print Plot
line_2 = plt.plot(years, mean['summer'], lw=0.5, color=colors[1], label="Summer") # Print Plot
line_3 = plt.plot(years, mean['autumn'], lw=0.5, color=colors[2], label="Autumn") # Print Plot
line_4 = plt.plot(years, mean['winter'], lw=0.5, color=colors[3], label="Winter") # Print Plot
plt.legend(loc="lower right")
plt.savefig("season_temp_decade.jpg") # Save Plot as jpg