This repository was archived by the owner on Aug 14, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathChartManager.py
More file actions
143 lines (123 loc) · 5.87 KB
/
Copy pathChartManager.py
File metadata and controls
143 lines (123 loc) · 5.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import altair as alt
import pandas as pd
alt.data_transformers.disable_max_rows()
# altair_viewer._global_viewer._use_bundled_js = False
# alt.data_transformers.enable('data_server')
class ChartManager():
def __init__(self):
self.df = None
self.Chart = None
#Thailand Map Chart
self.ThailandProvincesTopo = alt.topo_feature('https://raw.githubusercontent.com/cvibhagool/thailand-map/master/thailand-provinces.topojson', 'province')
self.obj_columns = [] #columns of object value for nomial type
self.int_columns = [] #columns of integer value for quantitative type
def setDataframe(self,dataframe):
self.df = dataframe
#select columns name each type
self.obj_columns = self.df.select_dtypes(include=['object']).columns.to_list()
self.int_columns = self.df.select_dtypes(include=['int']).columns.to_list()
def ColorSchema(self,dataframe,Measurement,Color:list):
#set color shades from max value
color = alt.Color(Measurement,
type= "quantitative",
scale = alt.Scale(
domain = [0,dataframe[Measurement].mean(),dataframe[Measurement].max()],
range = Color,
type = "linear")
)
return color
def Tooltip(self,ColumnNames:list):
#select tooltip type each column names
l = []
for col in ColumnNames:
t = "quantitative" if col in self.int_columns else "nominal"
l.append(alt.Tooltip(col, type= t))
return l
def SumDuplicateValue(self,df):
l = []
for y in list(set(df['year'])):
maxweeknum = df.loc[df['year'] == y]['weeknum'].max() #find last week in this year
#get dataframe with rows at last week using total_case each year
l.append(df.loc[(df['weeknum'] == maxweeknum) & (df['year'] == y)])
df = pd.concat(l, ignore_index=True)
#sum total_case and deatch each province
group = df.groupby('province').transform('sum')
#move to dataframe
df['total_case'] = group['total_case']
df['total_death'] = group['total_death']
df = df.drop_duplicates(subset=['province'])
return df
def dropAllandNone(self,df):
#drop All and None rows
df = df.drop(index=df[df["province"].isin(["All","None"])].index)
return df
def SetDatetime(self,df):
#Change value in date column to datetime type
df['date'] = pd.to_datetime(
df['year'].astype(str) + '-W' + df['weeknum'].astype(str) + '-0',
format='%G-W%V-%w')
df = df.sort_values(by=['date']).loc[df["province"]=="All"].reset_index(drop=True)
return df
def SumTotalCD(self,df):
#sum total_case and total_case of each year for all year to allcase and alldeath
df['allcase'] = 0
df['alldeath'] = 0
for index, row in df.iterrows():
if index == 0:
df.loc[index,'allcase'] = row['total_case']
casenextvalue = df.loc[index,'allcase']
df.loc[index,'alldeath'] = row['total_death']
deathnextvalue = df.loc[index,'alldeath']
elif index == df.shape[0] -1:
df.loc[index,'allcase'] = casenextvalue + row['new_case']
df.loc[index,'alldeath'] = deathnextvalue + row['new_death']
else:
df.loc[index,'allcase'] = casenextvalue + row['new_case']
casenextvalue = df.loc[index,'allcase']
df.loc[index,'alldeath'] = deathnextvalue + row['new_death']
deathnextvalue = df.loc[index,'alldeath']
return df
def ThailandTopoChart(self,Width,Height):
df = self.SumDuplicateValue(self.df)
df = self.dropAllandNone(df)
self.Chart = alt.Chart(self.ThailandProvincesTopo).mark_geoshape().encode(
color = self.ColorSchema(df,'total_case',['white','#E34234','#640000']),
tooltip = self.Tooltip(['properties.NAME_1','total_case','total_death'])
).transform_lookup(
lookup='properties.NAME_1',
from_ = alt.LookupData(df,'province',['total_case','total_death'])
).properties(
width=Width,
height=Height
)
self.Chart.save('ChartJSON/ThailandTopoChart.json')
return self.Chart
def BarChart(self):
df = self.df
df = self.dropAllandNone(df)
self.Chart = alt.Chart(df).mark_bar(clip=True).encode(
x = alt.X("province",type = "nominal", title= "จังหวัด"),
y = alt.Y("total_case",
type= "quantitative",
scale= alt.Scale(domain=[0,df["total_case"].max()]),
title= "ผู้ป่วยสะสม"),
tooltip = ["province","total_case","total_death"]
).facet( column = "region"
).resolve_scale(x = 'independent',y = 'independent')
self.Chart.save('ChartJSON/BarChart.json')
return self.Chart
def LineChart(self):
df = self.SetDatetime(self.df)
df = self.SumTotalCD(df)
self.Chart = alt.Chart(df).mark_line(
point=alt.OverlayMarkDef(
filled=False, fill="white")
).encode(
x=alt.X("date",type="temporal", title= "วัน"),
y=alt.Y(
alt.repeat("layer"), aggregate="mean",title="ผู้ติดเชื้อสะสมทั้งประเทศ"),
tooltip = ['date:T','allcase:Q','alldeath:Q'],
color=alt.datum(alt.repeat("layer")),
).repeat(layer=["allcase", "alldeath"])
self.Chart.save('ChartJSON/LineChart.json')
return self.Chart