/
defaults.py
219 lines (205 loc) · 6.16 KB
/
defaults.py
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
from functools import wraps
from typing import Callable, Union
import altair as alt
FONT_SIZE = 16
ANNOTATION_MARGIN = 16
HEIGHT = 300
WIDTH = "container"
REDUCED_HEIGHT = REDUCED_WIDTH = 60
SELECTOR_COLOR = "darkred"
TIME_FORMAT = "%I:%M %p on %A %b %e, %Y"
TIME_SELECTION_TOOLTIP = "Click and drag to select a time window"
FIELD_DEFINITIONS = {
"event_start": dict(
field="event_start",
type="temporal",
title=None,
axis={"labelOverlap": True, "labelSeparation": 1},
),
"event_end": dict(
field="event_end",
type="temporal",
title=None,
axis={"labelOverlap": True, "labelSeparation": 1},
),
"event_value": dict(
field="event_value",
type="quantitative",
),
"source": dict(
field="source",
type="nominal",
title="Source",
),
"full_date": dict(
field="full_date",
type="nominal",
title="Time and date",
),
}
SHADE_LAYER = {
"mark": {
"type": "bar",
"color": "#bbbbbb",
"opacity": 0.3,
"size": HEIGHT,
},
"encoding": {
"x": dict(
field="start",
type="temporal",
title=None,
),
"x2": dict(
field="end",
type="temporal",
title=None,
),
},
"params": [
{
"name": "highlight",
"select": {"type": "point", "on": "mouseover"},
},
{"name": "select", "select": "point"},
],
}
TEXT_LAYER = {
"mark": {
"type": "text",
"y": HEIGHT,
"dy": FONT_SIZE + ANNOTATION_MARGIN,
"baseline": "top",
"align": "left",
"fontSize": FONT_SIZE,
"fontStyle": "italic",
},
"encoding": {
"x": dict(
field="start",
type="temporal",
title=None,
),
"text": {"type": "nominal", "field": "content"},
"opacity": {
"condition": [
{
"param": "select",
"empty": False,
"value": 1,
},
{
"param": "highlight",
"empty": False,
"value": 1,
},
],
"value": 0,
},
},
}
LEGIBILITY_DEFAULTS = dict(
config=dict(
axis=dict(
titleFontSize=FONT_SIZE,
labelFontSize=FONT_SIZE,
),
axisY={"titleAngle": 0, "titleAlign": "left", "titleY": -15, "titleX": -40},
title=dict(
fontSize=FONT_SIZE,
),
),
encoding=dict(
color=dict(
dict(
legend=dict(
titleFontSize=FONT_SIZE,
labelFontSize=FONT_SIZE,
)
)
)
),
)
vega_lite_field_mapping = {
"title": "text",
"mark": "type",
}
def apply_chart_defaults(fn):
@wraps(fn)
def decorated_chart_specs(*args, **kwargs) -> dict:
""":returns: dict with vega-lite specs, even when applied to an Altair chart."""
dataset_name = kwargs.pop("dataset_name", None)
include_annotations = kwargs.pop("include_annotations", None)
if isinstance(fn, Callable):
# function that returns a chart specification
chart_specs: Union[dict, alt.TopLevelMixin] = fn(*args, **kwargs)
else:
# not a function, but a direct chart specification
chart_specs: Union[dict, alt.TopLevelMixin] = fn
if isinstance(chart_specs, alt.TopLevelMixin):
chart_specs = chart_specs.to_dict()
chart_specs.pop("$schema")
# Add transform function to calculate full date
if "transform" not in chart_specs:
chart_specs["transform"] = []
chart_specs["transform"].append(
{
"as": "full_date",
"calculate": f"timeFormat(datum.event_start, '{TIME_FORMAT}')",
}
)
if dataset_name:
chart_specs["data"] = {"name": dataset_name}
if include_annotations:
annotation_shades_layer = SHADE_LAYER
annotation_text_layer = TEXT_LAYER
annotation_shades_layer["data"] = {
"name": dataset_name + "_annotations"
}
annotation_text_layer["data"] = {"name": dataset_name + "_annotations"}
chart_specs = {
"layer": [
annotation_shades_layer,
chart_specs,
annotation_text_layer,
]
}
# Fall back to default height and width, if needed
if "height" not in chart_specs:
chart_specs["height"] = HEIGHT
if "width" not in chart_specs:
chart_specs["width"] = WIDTH
# Improve default legibility
chart_specs = merge_vega_lite_specs(
LEGIBILITY_DEFAULTS,
chart_specs,
)
return chart_specs
return decorated_chart_specs
def merge_vega_lite_specs(child: dict, parent: dict) -> dict:
"""Merge nested dictionaries, with child inheriting values from parent.
Child values are updated with parent values if they exist.
In case a field is a string and that field is updated with some dict,
the string is moved inside the dict under a field defined in vega_lite_field_mapping.
For example, 'title' becomes 'text' and 'mark' becomes 'type'.
"""
d = {}
for k in set().union(child, parent):
if k in parent and k in child:
if isinstance(child[k], str):
child[k] = {vega_lite_field_mapping.get(k, "type"): child[k]}
if isinstance(parent[k], str):
parent[k] = {vega_lite_field_mapping.get(k, "type"): parent[k]}
if (
k in parent
and isinstance(parent[k], dict)
and k in child
and isinstance(child[k], dict)
):
v = merge_vega_lite_specs(child[k], parent[k])
elif k in parent:
v = parent[k]
else:
v = child[k]
d[k] = v
return d