Skip to content

Commit

Permalink
#8 check minor changes of 4th rick.py
Browse files Browse the repository at this point in the history
  • Loading branch information
Zhangyixue1537 committed Dec 28, 2023
1 parent 2facbf2 commit 4fe70a9
Showing 1 changed file with 53 additions and 139 deletions.
192 changes: 53 additions & 139 deletions rick.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
# -*- coding: utf-8 -*-
#!/usr/bin/env python
"""
Version 0.8.0
"""

from psycopg2 import connect
Expand Down Expand Up @@ -91,12 +88,10 @@ def island(con):
"""

query = '''
SELECT
geom
FROM gis.zones_tts06
WHERE gta06 = 81
'''

island = gpd.GeoDataFrame.from_postgis(query, con, geom_col='geom')
Expand Down Expand Up @@ -127,7 +122,6 @@ def func():

def chloro_map(con, df, subway, island, lower, upper, title, **kwargs):
"""Creates a chloropleth map
Parameters
-----------
con : SQL connection object
Expand All @@ -146,14 +140,12 @@ def chloro_map(con, df, subway, island, lower, upper, title, **kwargs):
Unit to append to the end of the legend tick
nbins : int, optional, defualt: 2
Number of ticks in the colourmap
Returns
--------
fig
Matplotlib fig object
ax
Matplotlib ax object
"""

cmap = kwargs.get('cmap', colour.cmap)
Expand All @@ -163,7 +155,7 @@ def chloro_map(con, df, subway, island, lower, upper, title, **kwargs):
df.columns = ['geom', 'values']
light = '#d9d9d9'

fig, ax = plt.subplots(dpi=450.0)
fig, ax = plt.subplots(dpi=450.0, figsize=(12,12))
fig.set_size_inches(6.69,3.345)

ax.set_yticklabels([])
Expand All @@ -185,14 +177,14 @@ def chloro_map(con, df, subway, island, lower, upper, title, **kwargs):


props = dict(boxstyle='round', facecolor='w', alpha=0)
plt.text(0.775, 0.37, title, transform=ax.transAxes, wrap = True, fontsize=7, fontname = font.semibold,
verticalalignment='bottom', bbox=props, fontweight = 'bold') # Adding the Legend Title
plt.text(0.775, 0.37, title, transform=ax.transAxes, wrap = True, fontsize=7, fontname = font.normal,
verticalalignment='bottom', bbox=props, fontweight = 'semibold') # Adding the Legend Title


cax = fig.add_axes([0.718, 0.16, 0.01, 0.22]) # Size of colorbar

#rect = patches.Rectangle((0.76, 0.01),0.235,0.43,linewidth=0.5, transform=ax.transAxes, edgecolor=light,facecolor='none')
#ax.add_patch(rect)
rect = patches.Rectangle((0.76, 0.01),0.235,0.43,linewidth=0.5, transform=ax.transAxes, edgecolor=light,facecolor='none')
ax.add_patch(rect)

ax.margins(0.1)

Expand Down Expand Up @@ -260,8 +252,7 @@ def histogram_chart(data, ylab, xlab, nbin, **kwargs):
nbin = 10

plt.style.use('seaborn-whitegrid')
fig, ax = plt.subplots(1,1, dpi=450.0)
fig.set_size_inches(6.1, 4.2)
fig, ax = plt.subplots(1,1, figsize=(14,10))
ax.hist(data, bins=nbin, alpha=1.0, color=colour.purple)
ax.set_xlabel(xlab)
ax.set_ylabel(ylab)
Expand Down Expand Up @@ -298,10 +289,6 @@ def line_chart(data, ylab, xlab, **kwargs):
The increment of ticks on the y axis.
list_legends: list, optional (when baseline is ON)
List of legend names to show on plot
min_text : array of min-value text information, default is None
max_text : array of max-value text information, default is None
Returns
--------
Expand All @@ -320,11 +307,8 @@ def line_chart(data, ylab, xlab, **kwargs):
baseline = kwargs.get('baseline', None)
addedline1 = kwargs.get('addedline1', None)
addedline2 = kwargs.get('addedline2', None)
list_legends = kwargs.get('list_legends', None)
min_text = kwargs.get('min_text', None)
max_text = kwargs.get('max_text', None)
xticker_labels = kwargs.get('xticker_labels', None)
xticker_slots= kwargs.get('xticker_slots', None)
list_legends = kwargs.get('list_legends', None)

delta = (ymax - ymin)/4
i = 0
Expand All @@ -335,8 +319,7 @@ def line_chart(data, ylab, xlab, **kwargs):
break
yinc = kwargs.get('yinc', int(round(delta+1)*pow(10,i)))

fig, ax = plt.subplots(dpi=450.0)
fig.set_size_inches(6.1, 4.2)
fig, ax = plt.subplots(dpi=450.0, figsize=(12,12))
line, = ax.plot(data, linewidth=3, color = colour.purple)
if baseline is not None:
line_baseline, = ax.plot(baseline ,linewidth=3, color = colour.grey)
Expand All @@ -352,39 +335,28 @@ def line_chart(data, ylab, xlab, **kwargs):

ax.set_facecolor('xkcd:white')

plt.xlabel(xlab, fontsize=9, fontweight = 'bold', horizontalalignment='right', x=0, labelpad=10,
fontname = font.normal)
plt.xlabel(xlab, fontsize=9, fontweight = 'bold', horizontalalignment='right', x=0, labelpad=10, fontname = font.normal)

ax.grid(color='k', linestyle='-', linewidth=0.2)
plt.ylabel(ylab, fontsize=9, fontweight = 'bold',
horizontalalignment='right', y=1.0,
labelpad=10, fontname = font.normal)
fig.set_size_inches(6.1, 4.1)
plt.xticks(xticker_slots, fontsize=9, fontname = font.normal)
#plt.xticks(fontsize=9, fontname = font.normal)
plt.yticks(range(ymin, ymax + yinc, yinc), fontsize =9,
fontname = font.normal)


if (xticker_labels is not None):
list_major_labels = xticker_labels
list_major_ticks = xticker_slots
list_major_ticks = np.arange(0, len(list_major_labels), 1)
ax.xaxis.set_major_locator(ticker.FixedLocator(list_major_ticks))
ax.xaxis.set_major_formatter(ticker.FixedFormatter(list_major_labels))
#ax.tick_params(axis='x', which='major', colors = colour.light_grey, labelsize=7, rotation=0)
ax.tick_params(axis='x', which='major', colors = colour.light_grey, labelsize=7, rotation=45)
# ax.set_xticklabels(list_major_labels)


# Set text - min & max
props = dict(boxstyle='round, pad=0.4',edgecolor=colour.purple,
linewidth = 2, facecolor = 'w', alpha=1)
if (min_text is not None):
plt.text(min_text[0], min_text[1], int(data.min()), size=min_text[2], rotation=min_text[3],
ha="center", va="center", color='#660159', bbox=props)
if (max_text is not None):
plt.text(max_text[0], max_text[1], int(data.max()), size=max_text[2], rotation=max_text[3],
ha="center", va="center", color='#660159', bbox=props)





# Set lengends (if multiple lines)
if (baseline is not None):
ax.legend([line, line_baseline], list_legends, loc = 'best',
Expand All @@ -408,7 +380,6 @@ def line_chart(data, ylab, xlab, **kwargs):

def tow_chart(data, ylab, **kwargs):
"""Creates a 7 day time of week line chart. Each data point represents 1 hour out of 168 hours.
Parameters
-----------
data : array like or scalar
Expand All @@ -421,7 +392,6 @@ def tow_chart(data, ylab, **kwargs):
The minimum value of the y axis
yinc : int, optional
The increment of ticks on the y axis.
Returns
--------
fig
Expand All @@ -430,7 +400,6 @@ def tow_chart(data, ylab, **kwargs):
Matplotlib ax object
props
Dictionary of the text annotation properties
"""
import matplotlib.pyplot as plt
import matplotlib as mpl
Expand Down Expand Up @@ -480,33 +449,6 @@ def tow_chart(data, ylab, **kwargs):

ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
plt.yticks(range(ymin,upper+int(0.1*yinc), yinc), fontsize =9, fontname = font.normal)

# # Basic - Y ticks
# list_major_ticks = np.arange(0, 180, 12)
# list_major_labels = ['0','12','0','12','0','12','0','12','0','12','0','12','0','12','0']

# # Experiment-1 - Y ticks (every 3hrs)
# list_major_ticks = np.arange(0, 180, 3)
# list_major_labels = ['0','3','6','9','12','15','18','21',
# '0','3','6','9','12','15','18','21',
# '0','3','6','9','12','15','18','21',
# '0','3','6','9','12','15','18','21',
# '0','3','6','9','12','15','18','21',
# '0','3','6','9','12','15','18','21',
# '0','3','6','9','12','15','18','21',
# '0']

# # Experiment-2 - Y ticks (every 6hrs)
# list_major_ticks = np.arange(0, 180, 6)
# list_major_labels = ['0','6','12','18',
# '0','6','12','18',
# '0','6','12','18',
# '0','6','12','18',
# '0','6','12','18',
# '0','6','12','18',
# '0','6','12','18',
# '0']



# Experiment-3 - Y ticks (only 9H & 18H)
Expand Down Expand Up @@ -601,7 +543,7 @@ def stacked_chart(data_in, xlab, lab1, lab2, **kwargs):

ind = np.arange(len(data))

fig, ax = plt.subplots(dpi=450.0)
fig, ax = plt.subplots(dpi=450.0, figsize=(12,12))
fig.set_size_inches(6.1, len(data))
ax.grid(color='k', linestyle='-', linewidth=0.25)

Expand Down Expand Up @@ -652,7 +594,7 @@ def stacked_chart(data_in, xlab, lab1, lab2, **kwargs):

return fig, ax

def bar_chart(data_in, xlab, ylab, horizontal=False, **kwargs):
def bar_chart(data_in, xlab,**kwargs):
"""Creates a bar chart
Parameters
Expand All @@ -661,19 +603,15 @@ def bar_chart(data_in, xlab, ylab, horizontal=False, **kwargs):
Data for the bar chart. The dataframe must have 2 columns, the first representing the y ticks, and the second representing the data
xlab : str
Label for the x axis.
ylab : str
Label for the y axis.
horizontal: bool, Alignment of bar_chart
True if horizontal else vertical
xymax : int, optional, default is the max s value
xmax : int, optional, default is the max s value
The max value of the y axis
xymin : int, optional, default is 0
xmin : int, optional, default is 0
The minimum value of the x axis
precision : int, optional, default is -1
Decimal places in the annotations
xyinc : int, optional
The increment of ticks on the x axis/y axis depending on horizontal bool value.
xinc : int, optional
The increment of ticks on the x axis.
Returns
--------
Expand All @@ -688,84 +626,60 @@ def bar_chart(data_in, xlab, ylab, horizontal=False, **kwargs):

data.columns = ['name', 'values1']

xymin = kwargs.get('xymin', 0)
xymax = kwargs.get('xymax', None)
xmin = kwargs.get('xmin', 0)
xmax = kwargs.get('xmax', None)
precision = kwargs.get('precision', 0)

xymax_flag = True
if xymax == None:
xymax = data['values1'].max()
xymax_flag = False
xmax_flag = True
if xmax == None:
xmax = data['values1'].max()
xmax_flag = False

delta = (xymax - xymin)/4
delta = (xmax - xmin)/4
i = 0
while True:
if delta < 10:
break
delta /= 10
i += 1
xyinc = kwargs.get('xyinc', int(round(delta+1)*pow(10,i)))
xinc = kwargs.get('xinc', int(round(delta+1)*pow(10,i)))

if xymax_flag == True:
upper = xymax
if xmax_flag == True:
upper = xmax
else:
upper = int(4*xyinc+xymin)
upper = int(4*xinc+xmin)

ind = np.arange(len(data))

fig, ax = plt.subplots(dpi=450.0)
fig.set_size_inches(6.1, 4.2)
# fig.set_size_inches(6.1, len(data)*0.7)
fig, ax = plt.subplots(dpi=450.0, figsize=(12,12))
fig.set_size_inches(6.1, len(data)*0.7)
ax.grid(color='k', linestyle='-', linewidth=0.25)
if(horizontal):
p2 = ax.barh(ind, data['values1'], 0.75, align='center', color = colour.purple)
ax.xaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
ax.xaxis.grid(True)
ax.yaxis.grid(False)
ax.set_yticks(ind)
ax.set_xlim(0,upper)
ax.set_yticklabels(data['name'])
ax.set_xlabel(xlab, horizontalalignment='left', x=0, labelpad=10, fontname = font.normal, fontsize=10, fontweight = 'bold')
if (ylab is not None):
ax.set_ylabel(ylab, labelpad=10, fontname = font.normal, fontsize=10, fontweight = 'bold')
plt.xticks(range(xymin,upper+int(0.1*xyinc), xyinc), fontname = font.normal, fontsize =10)
plt.yticks( fontname = font.normal, fontsize =10)
else:
p2 = ax.bar(ind, data['values1'], 1.0, align='center', color = colour.purple)
ax.yaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))
ax.yaxis.grid(True)
ax.xaxis.grid(False)
ax.set_xticks(ind)
ax.set_ylim(0, upper)
ax.set_xticklabels(data['name'], rotation=0.0)
ax.set_ylabel(ylab, labelpad=10, fontname = font.normal, fontsize=10, fontweight = 'bold')
if (xlab is not None):
ax.set_xlabel(xlab, labelpad=10, fontname = font.normal, fontsize=10, fontweight = 'bold')
plt.yticks(range(xymin, upper+int(0.1*xyinc), xyinc), fontname = font.normal, fontsize =10)
plt.xticks( fontname = font.normal, fontsize =10)
p2 = ax.barh(ind, data['values1'], 0.75, align='center', color = colour.purple)
ax.xaxis.set_major_formatter(mpl.ticker.StrMethodFormatter('{x:,.0f}'))

ax.xaxis.grid(True)
ax.yaxis.grid(False)
ax.set_yticks(ind)
ax.set_xlim(0,upper)
ax.set_yticklabels(data['name'])
ax.set_xlabel(xlab, horizontalalignment='left', x=0, labelpad=10, fontname = font.normal, fontsize=10, fontweight = 'bold')


ax.set_facecolor('xkcd:white')
j=0

if precision < 1:
data['values1'] = data['values1'].astype(int)

j=0
if (horizontal == True and (precision != -1)):
for i in data['values1']:
if i < 0.1*upper:
ax.annotate(str(format(round(i, precision), ',')), xy=(i+0.015*upper, j-0.05), ha = 'left', color = 'k', fontname = font.normal, fontsize=10)
else:
ax.annotate(str(format(round(i, precision), ',')), xy=(i-0.015*upper, j-0.05), ha = 'right', color = 'w', fontname = font.normal, fontsize=10)
j=j+1
elif (horizontal == False and (precision != -1)):
for i in data['values1']:
if i < 0.1*upper:
ax.annotate(str(format(round(i, precision), ',')), xy=(j-0.15, i+0.015*upper), ha = 'left', color = 'k', fontname = font.normal, fontsize=10, rotation=90.)
else:
ax.annotate(str(format(round(i, precision), ',')), xy=(j+0.15, i-0.06*upper), ha = 'right', color = 'w', fontname = font.normal, fontsize=10, rotation=90.)
j=j+1
for i in data['values1']:
if i < 0.1*upper:
ax.annotate(str(format(round(i,precision), ',')), xy=(i+0.015*upper, j-0.05), ha = 'left', color = 'k', fontname = font.normal, fontsize=10)
else:
ax.annotate(str(format(round(i,precision), ',')), xy=(i-0.015*upper, j-0.05), ha = 'right', color = 'w', fontname = font.normal, fontsize=10)
j=j+1



plt.xticks(range(xmin,upper+int(0.1*xinc), xinc), fontname = font.normal, fontsize =10)
plt.yticks( fontname = font.normal, fontsize =10)

return fig, ax

0 comments on commit 4fe70a9

Please sign in to comment.