Skip to content

Instantly share code, notes, and snippets.

@KerryHalupka
KerryHalupka / colorbar_example1.py
Last active July 25, 2020 02:43
example imshow, default colormap
import numpy as np
import matplotlib.pyplot as plt
x, y = np.mgrid[-5:5:0.05, -5:5:0.05]
z = (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2))
fig, ax = plt.subplots(1,1)
im = ax.imshow(z)
fig.colorbar(im)
ax.yaxis.set_major_locator(plt.NullLocator()) # remove y axis ticks
@KerryHalupka
KerryHalupka / colorbar_example2.py
Created July 25, 2020 02:39
Test out different matplotlib colormaps
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, axes = plt.subplots(2,2, figsize=(10,10))
# the colormaps we'll be trying out
cmap_list = ['RdPu', 'spring', 'PRGn', 'gnuplot']
for ax, name in zip(axes.flatten(), cmap_list):
im = ax.imshow(z, aspect='auto', cmap=plt.get_cmap(name))
ax.yaxis.set_major_locator(plt.NullLocator()) # remove y axis ticks
ax.xaxis.set_major_locator(plt.NullLocator()) # remove x axis ticks
@KerryHalupka
KerryHalupka / color_conversion.py
Created July 25, 2020 03:10
Functions to convert between different color formats
def hex_to_rgb(value):
'''
Converts hex to rgb colours
value: string of 6 characters representing a hex colour.
Returns: list length 3 of RGB values'''
value = value.strip("#") # removes hash symbol if present
lv = len(value)
return tuple(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3))
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
def hex_to_rgb(value):
'''
Converts hex to rgb colours
value: string of 6 characters representing a hex colour.
Returns: list length 3 of RGB values'''
value = value.strip("#") # removes hash symbol if present
def get_continuous_cmap(hex_list, float_list=None):
''' creates and returns a color map that can be used in heat map figures.
If float_list is not provided, colour map graduates linearly between each color in hex_list.
If float_list is provided, each color in hex_list is mapped to the respective location in float_list.
Parameters
----------
hex_list: list of hex code strings
float_list: list of floats between 0 and 1, same length as hex_list. Must start with 0 and end with 1.
fig, ax = plt.subplots(1,1)
im = ax.imshow(z, cmap=get_continuous_cmap(hex_list, float_list=[0, 0.05, 0.5, 0.6, 0.85, 0.9, 0.92, 1]))
fig.colorbar(im)
ax.yaxis.set_major_locator(plt.NullLocator()) # remove y axis ticks
ax.xaxis.set_major_locator(plt.NullLocator()) # remove x axis ticks
x, y = np.mgrid[-5:5:0.05, -5:5:0.05]
z = (np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2))
z = 7*(z/z.max())-2 #shift range to between -2 and 5
center = 0
divnorm = mcolors.TwoSlopeNorm(vmin=z.min(),vcenter=center, vmax=z.max())
fig, ax = plt.subplots(1,1)
hex_list = ['#0091ad', '#d6f6eb', '#fdf1d2', '#faaaae', '#ff57bb']
im = ax.imshow(z, cmap=get_continuous_cmap(hex_list), norm=divnorm)
@KerryHalupka
KerryHalupka / choropleth_example1.py
Created July 27, 2020 10:52
Load in and display unemployment data
import geopandas as gpd
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import plotly.graph_objects as go
emp_df = pd.read_csv('./data/ABS_C16_G43_LGA_26072020234812892.csv') #read in the data
emp_df = emp_df[['LGA_2016', 'Labour force status', 'Region', 'Value']] #select only the columns we need
emp_df['LGA_2016'] = emp_df['LGA_2016'].astype('str') # we will join on this axis, so both dataframes need this to be the same type
@KerryHalupka
KerryHalupka / choropleth_example2.py
Created July 27, 2020 11:08
Load shapefile at LGA granularity.
lga_gdf = gpd.read_file('./data/1270055003_lga_2020_aust_shp/LGA_2020_AUST.shp') #load the data using Geopandas
lga_gdf = lga_gdf[lga_gdf['STE_NAME16']=='Victoria'] #Select the data for the state of Victoria
lga_gdf['LGA_CODE20'] = lga_gdf['LGA_CODE20'].astype('str') # we will join on this axis, so both dataframes need this to be the same type
lga_gdf.head()
@KerryHalupka
KerryHalupka / choropleth_example3.py
Created July 27, 2020 11:44
Merge dataframes and display using geopandas
df_merged = pd.merge(lga_gdf[['LGA_CODE20', 'geometry', 'LGA_NAME20']], emp_df[['LGA_2016', 'percent_unemployed']], left_on='LGA_CODE20', right_on='LGA_2016', how='left')
df_merged = df_merged.dropna(subset=['percent_unemployed', 'LGA_CODE20', 'geometry'])
# OPTIONAL: Display using geopandas
fig, ax = plt.subplots(1,1, figsize=(20,20))
divider = make_axes_locatable(ax)
tmp = df_merged.copy()
tmp['percent_unemployed'] = tmp['percent_unemployed']*100 #To display percentages
cax = divider.append_axes("right", size="3%", pad=-1) #resize the colorbar
tmp.plot(column='percent_unemployed', ax=ax,cax=cax, legend=True,