Skip to content

Instantly share code, notes, and snippets.

@kdorr
Last active Aug 10, 2018
Embed
What would you like to do?
Class structure to parse Altair Charts and store data and metadata.
from ._data import (_locate_channel_data, _locate_channel_axis, _locate_channel_field, _locate_channel_scale,
_locate_channel_dtype, _convert_to_mpl_date)
class Channel(object):
"""
Stores relevant encoding channel information.
Attributes
----------
channel : str
data : np.array
axis : dict
bin
field : str
scale : dict
sort
stack
timeUnit
title
type : str
"""
def __init__(self, channel_name, alt_chart, df):
self.channel = channel_name # Not stored in the channel's information in Altair, but useful to have
self.data = _locate_channel_data(alt_chart, channel_name) # Not stored in the channel's information in Altair, but useful to have
self.axis = _locate_channel_axis(alt_chart, channel_name)
self.bin = None
self.field = _locate_channel_field(alt_chart, channel_name)
self.scale = _locate_channel_scale(alt_chart, channel_name)
self.sort = None
self.stack = None
self.timeUnit = None
self.title = None
self.type = _locate_channel_dtype(alt_chart, channel_name)
if self.type == 'temporal':
self.data = _convert_to_mpl_date(self.data)
class Chart(object):
"""
Stores Altair chart information usefully. Use this class for initially converting the Altair chart.
Attributes
----------
data : pd.DataFrame
mark : str
encoding : dict of Channels
"""
def __init__(self, alt_chart):
_normalize_data(alt_chart)
self.data = alt_chart.data
self.mark = alt_chart.mark
self.encoding = {}
for k, v in alt_chart.to_dict()['encoding'].items():
self.encoding[k] = Channel(k, alt_chart, self.data) # Create a Channel for each present encoding channel.
ALTAIR_ENCODINGS = ['color', 'detail', 'fill', 'href', 'key', 'latitude', 'latitude2', 'longitude', 'longitude2',
'opacity', 'order', 'shape', 'size', 'stroke', 'text', 'tooltip', 'x', 'x2', 'y', 'y2']
for i in ALTAIR_ENCODINGS:
if i not in alt_chart.to_dict()['encoding'].keys():
self.encoding[i] = None # So we can have a consistent way to deal with channels that are possible in
# Altair charts in general, but not used in this one.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment