id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
233,400 | has2k1/plotnine | plotnine/guides/guide_colorbar.py | guide_colorbar.create_geoms | def create_geoms(self, plot):
"""
This guide is not geom based
Return self if colorbar will be drawn and None if not.
"""
for l in plot.layers:
exclude = set()
if isinstance(l.show_legend, dict):
l.show_legend = rename_aesthetics(l.show_legend)
exclude = {ae for ae, val in l.show_legend.items()
if not val}
elif l.show_legend not in (None, True):
continue
matched = self.legend_aesthetics(l, plot)
# layer uses guide
if set(matched) - exclude:
break
# no break, no layer uses this guide
else:
return None
return self | python | def create_geoms(self, plot):
for l in plot.layers:
exclude = set()
if isinstance(l.show_legend, dict):
l.show_legend = rename_aesthetics(l.show_legend)
exclude = {ae for ae, val in l.show_legend.items()
if not val}
elif l.show_legend not in (None, True):
continue
matched = self.legend_aesthetics(l, plot)
# layer uses guide
if set(matched) - exclude:
break
# no break, no layer uses this guide
else:
return None
return self | [
"def",
"create_geoms",
"(",
"self",
",",
"plot",
")",
":",
"for",
"l",
"in",
"plot",
".",
"layers",
":",
"exclude",
"=",
"set",
"(",
")",
"if",
"isinstance",
"(",
"l",
".",
"show_legend",
",",
"dict",
")",
":",
"l",
".",
"show_legend",
"=",
"rename... | This guide is not geom based
Return self if colorbar will be drawn and None if not. | [
"This",
"guide",
"is",
"not",
"geom",
"based"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide_colorbar.py#L108-L132 |
233,401 | has2k1/plotnine | plotnine/guides/guide_colorbar.py | MyAuxTransformBox.draw | def draw(self, renderer):
"""
Draw the children
"""
dpi_cor = renderer.points_to_pixels(1.)
self.dpi_transform.clear()
self.dpi_transform.scale(dpi_cor, dpi_cor)
for c in self._children:
c.draw(renderer)
self.stale = False | python | def draw(self, renderer):
dpi_cor = renderer.points_to_pixels(1.)
self.dpi_transform.clear()
self.dpi_transform.scale(dpi_cor, dpi_cor)
for c in self._children:
c.draw(renderer)
self.stale = False | [
"def",
"draw",
"(",
"self",
",",
"renderer",
")",
":",
"dpi_cor",
"=",
"renderer",
".",
"points_to_pixels",
"(",
"1.",
")",
"self",
".",
"dpi_transform",
".",
"clear",
"(",
")",
"self",
".",
"dpi_transform",
".",
"scale",
"(",
"dpi_cor",
",",
"dpi_cor",
... | Draw the children | [
"Draw",
"the",
"children"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide_colorbar.py#L404-L415 |
233,402 | has2k1/plotnine | plotnine/themes/themeable.py | themeable.from_class_name | def from_class_name(name, theme_element):
"""
Create an themeable by name
Parameters
----------
name : str
Class name
theme_element : element object
One of :class:`element_line`, :class:`element_rect`,
:class:`element_text` or :class:`element_blank`
Returns
-------
out : Themeable
"""
msg = "No such themeable element {}".format(name)
try:
klass = themeable._registry[name]
except KeyError:
raise PlotnineError(msg)
if not issubclass(klass, themeable):
raise PlotnineError(msg)
return klass(theme_element) | python | def from_class_name(name, theme_element):
msg = "No such themeable element {}".format(name)
try:
klass = themeable._registry[name]
except KeyError:
raise PlotnineError(msg)
if not issubclass(klass, themeable):
raise PlotnineError(msg)
return klass(theme_element) | [
"def",
"from_class_name",
"(",
"name",
",",
"theme_element",
")",
":",
"msg",
"=",
"\"No such themeable element {}\"",
".",
"format",
"(",
"name",
")",
"try",
":",
"klass",
"=",
"themeable",
".",
"_registry",
"[",
"name",
"]",
"except",
"KeyError",
":",
"rai... | Create an themeable by name
Parameters
----------
name : str
Class name
theme_element : element object
One of :class:`element_line`, :class:`element_rect`,
:class:`element_text` or :class:`element_blank`
Returns
-------
out : Themeable | [
"Create",
"an",
"themeable",
"by",
"name"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/themes/themeable.py#L96-L121 |
233,403 | has2k1/plotnine | plotnine/themes/themeable.py | themeable.merge | def merge(self, other):
"""
Merge properties of other into self
Raises ValueError if any them are a blank
"""
if self.is_blank() or other.is_blank():
raise ValueError('Cannot merge if there is a blank.')
else:
self.properties.update(other.properties) | python | def merge(self, other):
if self.is_blank() or other.is_blank():
raise ValueError('Cannot merge if there is a blank.')
else:
self.properties.update(other.properties) | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"is_blank",
"(",
")",
"or",
"other",
".",
"is_blank",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Cannot merge if there is a blank.'",
")",
"else",
":",
"self",
".",
"properties",
"... | Merge properties of other into self
Raises ValueError if any them are a blank | [
"Merge",
"properties",
"of",
"other",
"into",
"self"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/themes/themeable.py#L129-L138 |
233,404 | has2k1/plotnine | plotnine/themes/themeable.py | Themeables.update | def update(self, other):
"""
Update themeables with those from `other`
This method takes care of inserting the `themeable`
into the underlying dictionary. Before doing the
insertion, any existing themeables that will be
affected by a new from `other` will either be merged
or removed. This makes sure that a general themeable
of type :class:`text` can be added to override an
existing specific one of type :class:`axis_text_x`.
"""
for new in other.values():
new_key = new.__class__.__name__
# 1st in the mro is self, the
# last 2 are (themeable, object)
for child in new.__class__.mro()[1:-2]:
child_key = child.__name__
try:
self[child_key].merge(new)
except KeyError:
pass
except ValueError:
# Blank child is will be overridden
del self[child_key]
try:
self[new_key].merge(new)
except (KeyError, ValueError):
# Themeable type is new or
# could not merge blank element.
self[new_key] = new | python | def update(self, other):
for new in other.values():
new_key = new.__class__.__name__
# 1st in the mro is self, the
# last 2 are (themeable, object)
for child in new.__class__.mro()[1:-2]:
child_key = child.__name__
try:
self[child_key].merge(new)
except KeyError:
pass
except ValueError:
# Blank child is will be overridden
del self[child_key]
try:
self[new_key].merge(new)
except (KeyError, ValueError):
# Themeable type is new or
# could not merge blank element.
self[new_key] = new | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"for",
"new",
"in",
"other",
".",
"values",
"(",
")",
":",
"new_key",
"=",
"new",
".",
"__class__",
".",
"__name__",
"# 1st in the mro is self, the",
"# last 2 are (themeable, object)",
"for",
"child",
"in"... | Update themeables with those from `other`
This method takes care of inserting the `themeable`
into the underlying dictionary. Before doing the
insertion, any existing themeables that will be
affected by a new from `other` will either be merged
or removed. This makes sure that a general themeable
of type :class:`text` can be added to override an
existing specific one of type :class:`axis_text_x`. | [
"Update",
"themeables",
"with",
"those",
"from",
"other"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/themes/themeable.py#L225-L256 |
233,405 | has2k1/plotnine | plotnine/themes/themeable.py | Themeables.values | def values(self):
"""
Return a list themeables sorted in reverse based
on the their depth in the inheritance hierarchy.
The sorting is key applying and merging the themeables
so that they do not clash i.e :class:`axis_line`
applied before :class:`axis_line_x`.
"""
def key(th):
return len(th.__class__.__mro__)
return sorted(dict.values(self), key=key, reverse=True) | python | def values(self):
def key(th):
return len(th.__class__.__mro__)
return sorted(dict.values(self), key=key, reverse=True) | [
"def",
"values",
"(",
"self",
")",
":",
"def",
"key",
"(",
"th",
")",
":",
"return",
"len",
"(",
"th",
".",
"__class__",
".",
"__mro__",
")",
"return",
"sorted",
"(",
"dict",
".",
"values",
"(",
"self",
")",
",",
"key",
"=",
"key",
",",
"reverse"... | Return a list themeables sorted in reverse based
on the their depth in the inheritance hierarchy.
The sorting is key applying and merging the themeables
so that they do not clash i.e :class:`axis_line`
applied before :class:`axis_line_x`. | [
"Return",
"a",
"list",
"themeables",
"sorted",
"in",
"reverse",
"based",
"on",
"the",
"their",
"depth",
"in",
"the",
"inheritance",
"hierarchy",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/themes/themeable.py#L258-L270 |
233,406 | has2k1/plotnine | plotnine/positions/position.py | position.setup_data | def setup_data(self, data, params):
"""
Verify & return data
"""
check_required_aesthetics(
self.REQUIRED_AES,
data.columns,
self.__class__.__name__)
return data | python | def setup_data(self, data, params):
check_required_aesthetics(
self.REQUIRED_AES,
data.columns,
self.__class__.__name__)
return data | [
"def",
"setup_data",
"(",
"self",
",",
"data",
",",
"params",
")",
":",
"check_required_aesthetics",
"(",
"self",
".",
"REQUIRED_AES",
",",
"data",
".",
"columns",
",",
"self",
".",
"__class__",
".",
"__name__",
")",
"return",
"data"
] | Verify & return data | [
"Verify",
"&",
"return",
"data"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/positions/position.py#L24-L32 |
233,407 | has2k1/plotnine | plotnine/positions/position.py | position.compute_layer | def compute_layer(cls, data, params, layout):
"""
Compute position for the layer in all panels
Positions can override this function instead of
`compute_panel` if the position computations are
independent of the panel. i.e when not colliding
"""
def fn(pdata):
"""
Helper compute function
"""
# Given data belonging to a specific panel, grab
# the corresponding scales and call the method
# that does the real computation
if len(pdata) == 0:
return pdata
scales = layout.get_scales(pdata['PANEL'].iat[0])
return cls.compute_panel(pdata, scales, params)
return groupby_apply(data, 'PANEL', fn) | python | def compute_layer(cls, data, params, layout):
def fn(pdata):
"""
Helper compute function
"""
# Given data belonging to a specific panel, grab
# the corresponding scales and call the method
# that does the real computation
if len(pdata) == 0:
return pdata
scales = layout.get_scales(pdata['PANEL'].iat[0])
return cls.compute_panel(pdata, scales, params)
return groupby_apply(data, 'PANEL', fn) | [
"def",
"compute_layer",
"(",
"cls",
",",
"data",
",",
"params",
",",
"layout",
")",
":",
"def",
"fn",
"(",
"pdata",
")",
":",
"\"\"\"\n Helper compute function\n \"\"\"",
"# Given data belonging to a specific panel, grab",
"# the corresponding scales and... | Compute position for the layer in all panels
Positions can override this function instead of
`compute_panel` if the position computations are
independent of the panel. i.e when not colliding | [
"Compute",
"position",
"for",
"the",
"layer",
"in",
"all",
"panels"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/positions/position.py#L35-L55 |
233,408 | has2k1/plotnine | plotnine/positions/position.py | position.compute_panel | def compute_panel(cls, data, scales, params):
"""
Positions must override this function
Notes
-----
Make necessary adjustments to the columns in the dataframe.
Create the position transformation functions and
use self.transform_position() do the rest.
See Also
--------
position_jitter.compute_panel
"""
msg = '{} needs to implement this method'
raise NotImplementedError(msg.format(cls.__name__)) | python | def compute_panel(cls, data, scales, params):
msg = '{} needs to implement this method'
raise NotImplementedError(msg.format(cls.__name__)) | [
"def",
"compute_panel",
"(",
"cls",
",",
"data",
",",
"scales",
",",
"params",
")",
":",
"msg",
"=",
"'{} needs to implement this method'",
"raise",
"NotImplementedError",
"(",
"msg",
".",
"format",
"(",
"cls",
".",
"__name__",
")",
")"
] | Positions must override this function
Notes
-----
Make necessary adjustments to the columns in the dataframe.
Create the position transformation functions and
use self.transform_position() do the rest.
See Also
--------
position_jitter.compute_panel | [
"Positions",
"must",
"override",
"this",
"function"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/positions/position.py#L58-L74 |
233,409 | has2k1/plotnine | plotnine/positions/position.py | position.transform_position | def transform_position(data, trans_x=None, trans_y=None):
"""
Transform all the variables that map onto the x and y scales.
Parameters
----------
data : dataframe
trans_x : function
Transforms x scale mappings
Takes one argument, either a scalar or an array-type
trans_y : function
Transforms y scale mappings
Takes one argument, either a scalar or an array-type
"""
# Aesthetics that map onto the x and y scales
X = {'x', 'xmin', 'xmax', 'xend', 'xintercept'}
Y = {'y', 'ymin', 'ymax', 'yend', 'yintercept'}
if trans_x:
xs = [name for name in data.columns if name in X]
data[xs] = data[xs].apply(trans_x)
if trans_y:
ys = [name for name in data.columns if name in Y]
data[ys] = data[ys].apply(trans_y)
return data | python | def transform_position(data, trans_x=None, trans_y=None):
# Aesthetics that map onto the x and y scales
X = {'x', 'xmin', 'xmax', 'xend', 'xintercept'}
Y = {'y', 'ymin', 'ymax', 'yend', 'yintercept'}
if trans_x:
xs = [name for name in data.columns if name in X]
data[xs] = data[xs].apply(trans_x)
if trans_y:
ys = [name for name in data.columns if name in Y]
data[ys] = data[ys].apply(trans_y)
return data | [
"def",
"transform_position",
"(",
"data",
",",
"trans_x",
"=",
"None",
",",
"trans_y",
"=",
"None",
")",
":",
"# Aesthetics that map onto the x and y scales",
"X",
"=",
"{",
"'x'",
",",
"'xmin'",
",",
"'xmax'",
",",
"'xend'",
",",
"'xintercept'",
"}",
"Y",
"... | Transform all the variables that map onto the x and y scales.
Parameters
----------
data : dataframe
trans_x : function
Transforms x scale mappings
Takes one argument, either a scalar or an array-type
trans_y : function
Transforms y scale mappings
Takes one argument, either a scalar or an array-type | [
"Transform",
"all",
"the",
"variables",
"that",
"map",
"onto",
"the",
"x",
"and",
"y",
"scales",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/positions/position.py#L77-L103 |
233,410 | has2k1/plotnine | plotnine/positions/position.py | position.from_geom | def from_geom(geom):
"""
Create and return a position object for the geom
Parameters
----------
geom : geom
An instantiated geom object.
Returns
-------
out : position
A position object
Raises :class:`PlotnineError` if unable to create a `position`.
"""
name = geom.params['position']
if issubclass(type(name), position):
return name
if isinstance(name, type) and issubclass(name, position):
klass = name
elif is_string(name):
if not name.startswith('position_'):
name = 'position_{}'.format(name)
klass = Registry[name]
else:
raise PlotnineError(
'Unknown position of type {}'.format(type(name)))
return klass() | python | def from_geom(geom):
name = geom.params['position']
if issubclass(type(name), position):
return name
if isinstance(name, type) and issubclass(name, position):
klass = name
elif is_string(name):
if not name.startswith('position_'):
name = 'position_{}'.format(name)
klass = Registry[name]
else:
raise PlotnineError(
'Unknown position of type {}'.format(type(name)))
return klass() | [
"def",
"from_geom",
"(",
"geom",
")",
":",
"name",
"=",
"geom",
".",
"params",
"[",
"'position'",
"]",
"if",
"issubclass",
"(",
"type",
"(",
"name",
")",
",",
"position",
")",
":",
"return",
"name",
"if",
"isinstance",
"(",
"name",
",",
"type",
")",
... | Create and return a position object for the geom
Parameters
----------
geom : geom
An instantiated geom object.
Returns
-------
out : position
A position object
Raises :class:`PlotnineError` if unable to create a `position`. | [
"Create",
"and",
"return",
"a",
"position",
"object",
"for",
"the",
"geom"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/positions/position.py#L106-L136 |
233,411 | has2k1/plotnine | plotnine/scales/scales.py | make_scale | def make_scale(ae, series, *args, **kwargs):
"""
Return a proper scale object for the series
The scale is for the aesthetic ae, and args & kwargs
are passed on to the scale creating class
"""
stype = scale_type(series)
# filter parameters by scale type
if stype == 'discrete':
with suppress(KeyError):
del kwargs['trans']
scale_name = 'scale_{}_{}'.format(ae, stype)
scale_klass = Registry[scale_name]
return scale_klass(*args, **kwargs) | python | def make_scale(ae, series, *args, **kwargs):
stype = scale_type(series)
# filter parameters by scale type
if stype == 'discrete':
with suppress(KeyError):
del kwargs['trans']
scale_name = 'scale_{}_{}'.format(ae, stype)
scale_klass = Registry[scale_name]
return scale_klass(*args, **kwargs) | [
"def",
"make_scale",
"(",
"ae",
",",
"series",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stype",
"=",
"scale_type",
"(",
"series",
")",
"# filter parameters by scale type",
"if",
"stype",
"==",
"'discrete'",
":",
"with",
"suppress",
"(",
"KeyEr... | Return a proper scale object for the series
The scale is for the aesthetic ae, and args & kwargs
are passed on to the scale creating class | [
"Return",
"a",
"proper",
"scale",
"object",
"for",
"the",
"series"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L293-L309 |
233,412 | has2k1/plotnine | plotnine/scales/scales.py | Scales.append | def append(self, sc):
"""
Add scale 'sc' and remove any previous
scales that cover the same aesthetics
"""
ae = sc.aesthetics[0]
cover_ae = self.find(ae)
if any(cover_ae):
warn(_TPL_DUPLICATE_SCALE.format(ae), PlotnineWarning)
idx = cover_ae.index(True)
self.pop(idx)
# super() does not work well with reloads
list.append(self, sc) | python | def append(self, sc):
ae = sc.aesthetics[0]
cover_ae = self.find(ae)
if any(cover_ae):
warn(_TPL_DUPLICATE_SCALE.format(ae), PlotnineWarning)
idx = cover_ae.index(True)
self.pop(idx)
# super() does not work well with reloads
list.append(self, sc) | [
"def",
"append",
"(",
"self",
",",
"sc",
")",
":",
"ae",
"=",
"sc",
".",
"aesthetics",
"[",
"0",
"]",
"cover_ae",
"=",
"self",
".",
"find",
"(",
"ae",
")",
"if",
"any",
"(",
"cover_ae",
")",
":",
"warn",
"(",
"_TPL_DUPLICATE_SCALE",
".",
"format",
... | Add scale 'sc' and remove any previous
scales that cover the same aesthetics | [
"Add",
"scale",
"sc",
"and",
"remove",
"any",
"previous",
"scales",
"that",
"cover",
"the",
"same",
"aesthetics"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L20-L32 |
233,413 | has2k1/plotnine | plotnine/scales/scales.py | Scales.input | def input(self):
"""
Return a list of all the aesthetics covered by
the scales.
"""
lst = [s.aesthetics for s in self]
return list(itertools.chain(*lst)) | python | def input(self):
lst = [s.aesthetics for s in self]
return list(itertools.chain(*lst)) | [
"def",
"input",
"(",
"self",
")",
":",
"lst",
"=",
"[",
"s",
".",
"aesthetics",
"for",
"s",
"in",
"self",
"]",
"return",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"lst",
")",
")"
] | Return a list of all the aesthetics covered by
the scales. | [
"Return",
"a",
"list",
"of",
"all",
"the",
"aesthetics",
"covered",
"by",
"the",
"scales",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L41-L47 |
233,414 | has2k1/plotnine | plotnine/scales/scales.py | Scales.get_scales | def get_scales(self, aesthetic):
"""
Return the scale for the aesthetic or None if there
isn't one.
These are the scales specified by the user e.g
`ggplot() + scale_x_continuous()`
or those added by default during the plot building
process
"""
bool_lst = self.find(aesthetic)
try:
idx = bool_lst.index(True)
return self[idx]
except ValueError:
return None | python | def get_scales(self, aesthetic):
bool_lst = self.find(aesthetic)
try:
idx = bool_lst.index(True)
return self[idx]
except ValueError:
return None | [
"def",
"get_scales",
"(",
"self",
",",
"aesthetic",
")",
":",
"bool_lst",
"=",
"self",
".",
"find",
"(",
"aesthetic",
")",
"try",
":",
"idx",
"=",
"bool_lst",
".",
"index",
"(",
"True",
")",
"return",
"self",
"[",
"idx",
"]",
"except",
"ValueError",
... | Return the scale for the aesthetic or None if there
isn't one.
These are the scales specified by the user e.g
`ggplot() + scale_x_continuous()`
or those added by default during the plot building
process | [
"Return",
"the",
"scale",
"for",
"the",
"aesthetic",
"or",
"None",
"if",
"there",
"isn",
"t",
"one",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L49-L64 |
233,415 | has2k1/plotnine | plotnine/scales/scales.py | Scales.non_position_scales | def non_position_scales(self):
"""
Return a list of the non-position scales that
are present
"""
l = [s for s in self
if not ('x' in s.aesthetics) and not ('y' in s.aesthetics)]
return Scales(l) | python | def non_position_scales(self):
l = [s for s in self
if not ('x' in s.aesthetics) and not ('y' in s.aesthetics)]
return Scales(l) | [
"def",
"non_position_scales",
"(",
"self",
")",
":",
"l",
"=",
"[",
"s",
"for",
"s",
"in",
"self",
"if",
"not",
"(",
"'x'",
"in",
"s",
".",
"aesthetics",
")",
"and",
"not",
"(",
"'y'",
"in",
"s",
".",
"aesthetics",
")",
"]",
"return",
"Scales",
"... | Return a list of the non-position scales that
are present | [
"Return",
"a",
"list",
"of",
"the",
"non",
"-",
"position",
"scales",
"that",
"are",
"present"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L80-L87 |
233,416 | has2k1/plotnine | plotnine/scales/scales.py | Scales.position_scales | def position_scales(self):
"""
Return a list of the position scales that are present
"""
l = [s for s in self
if ('x' in s.aesthetics) or ('y' in s.aesthetics)]
return Scales(l) | python | def position_scales(self):
l = [s for s in self
if ('x' in s.aesthetics) or ('y' in s.aesthetics)]
return Scales(l) | [
"def",
"position_scales",
"(",
"self",
")",
":",
"l",
"=",
"[",
"s",
"for",
"s",
"in",
"self",
"if",
"(",
"'x'",
"in",
"s",
".",
"aesthetics",
")",
"or",
"(",
"'y'",
"in",
"s",
".",
"aesthetics",
")",
"]",
"return",
"Scales",
"(",
"l",
")"
] | Return a list of the position scales that are present | [
"Return",
"a",
"list",
"of",
"the",
"position",
"scales",
"that",
"are",
"present"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L89-L95 |
233,417 | has2k1/plotnine | plotnine/scales/scales.py | Scales.train_df | def train_df(self, df, drop=False):
"""
Train scales from a dataframe
"""
if (len(df) == 0) or (len(self) == 0):
return df
# Each scale trains the columns it understands
for sc in self:
sc.train_df(df)
return df | python | def train_df(self, df, drop=False):
if (len(df) == 0) or (len(self) == 0):
return df
# Each scale trains the columns it understands
for sc in self:
sc.train_df(df)
return df | [
"def",
"train_df",
"(",
"self",
",",
"df",
",",
"drop",
"=",
"False",
")",
":",
"if",
"(",
"len",
"(",
"df",
")",
"==",
"0",
")",
"or",
"(",
"len",
"(",
"self",
")",
"==",
"0",
")",
":",
"return",
"df",
"# Each scale trains the columns it understands... | Train scales from a dataframe | [
"Train",
"scales",
"from",
"a",
"dataframe"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L173-L183 |
233,418 | has2k1/plotnine | plotnine/scales/scales.py | Scales.map_df | def map_df(self, df):
"""
Map values from a dataframe.
Returns dataframe
"""
if (len(df) == 0) or (len(self) == 0):
return df
# Each scale maps the columns it understands
for sc in self:
df = sc.map_df(df)
return df | python | def map_df(self, df):
if (len(df) == 0) or (len(self) == 0):
return df
# Each scale maps the columns it understands
for sc in self:
df = sc.map_df(df)
return df | [
"def",
"map_df",
"(",
"self",
",",
"df",
")",
":",
"if",
"(",
"len",
"(",
"df",
")",
"==",
"0",
")",
"or",
"(",
"len",
"(",
"self",
")",
"==",
"0",
")",
":",
"return",
"df",
"# Each scale maps the columns it understands",
"for",
"sc",
"in",
"self",
... | Map values from a dataframe.
Returns dataframe | [
"Map",
"values",
"from",
"a",
"dataframe",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L185-L197 |
233,419 | has2k1/plotnine | plotnine/scales/scales.py | Scales.transform_df | def transform_df(self, df):
"""
Transform values in a dataframe.
Returns dataframe
"""
if (len(df) == 0) or (len(self) == 0):
return df
# Each scale transforms the columns it understands
for sc in self:
df = sc.transform_df(df)
return df | python | def transform_df(self, df):
if (len(df) == 0) or (len(self) == 0):
return df
# Each scale transforms the columns it understands
for sc in self:
df = sc.transform_df(df)
return df | [
"def",
"transform_df",
"(",
"self",
",",
"df",
")",
":",
"if",
"(",
"len",
"(",
"df",
")",
"==",
"0",
")",
"or",
"(",
"len",
"(",
"self",
")",
"==",
"0",
")",
":",
"return",
"df",
"# Each scale transforms the columns it understands",
"for",
"sc",
"in",... | Transform values in a dataframe.
Returns dataframe | [
"Transform",
"values",
"in",
"a",
"dataframe",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L199-L211 |
233,420 | has2k1/plotnine | plotnine/scales/scales.py | Scales.add_defaults | def add_defaults(self, data, aesthetics):
"""
Add default scales for the aesthetics if none are
present
Scales are added only if the aesthetic is mapped to
a column in the dataframe. This function may have to be
called separately after evaluating the aesthetics.
"""
if not aesthetics:
return
# aesthetics with scales
aws = set()
if self:
for s in (set(sc.aesthetics) for sc in self):
aws.update(s)
# aesthetics that do not have scales present
# We preserve the order of the aesthetics
new_aesthetics = [x for x in aesthetics.keys() if x not in aws]
if not new_aesthetics:
return
# If a new aesthetic corresponds to a column in the data
# frame, find a default scale for the type of data in that
# column
seen = set()
for ae in new_aesthetics:
col = aesthetics[ae]
if col not in data:
col = ae
scale_var = aes_to_scale(ae)
if self.get_scales(scale_var):
continue
seen.add(scale_var)
try:
sc = make_scale(scale_var, data[col])
except PlotnineError:
# Skip aesthetics with no scales (e.g. group, order, etc)
continue
self.append(sc) | python | def add_defaults(self, data, aesthetics):
if not aesthetics:
return
# aesthetics with scales
aws = set()
if self:
for s in (set(sc.aesthetics) for sc in self):
aws.update(s)
# aesthetics that do not have scales present
# We preserve the order of the aesthetics
new_aesthetics = [x for x in aesthetics.keys() if x not in aws]
if not new_aesthetics:
return
# If a new aesthetic corresponds to a column in the data
# frame, find a default scale for the type of data in that
# column
seen = set()
for ae in new_aesthetics:
col = aesthetics[ae]
if col not in data:
col = ae
scale_var = aes_to_scale(ae)
if self.get_scales(scale_var):
continue
seen.add(scale_var)
try:
sc = make_scale(scale_var, data[col])
except PlotnineError:
# Skip aesthetics with no scales (e.g. group, order, etc)
continue
self.append(sc) | [
"def",
"add_defaults",
"(",
"self",
",",
"data",
",",
"aesthetics",
")",
":",
"if",
"not",
"aesthetics",
":",
"return",
"# aesthetics with scales",
"aws",
"=",
"set",
"(",
")",
"if",
"self",
":",
"for",
"s",
"in",
"(",
"set",
"(",
"sc",
".",
"aesthetic... | Add default scales for the aesthetics if none are
present
Scales are added only if the aesthetic is mapped to
a column in the dataframe. This function may have to be
called separately after evaluating the aesthetics. | [
"Add",
"default",
"scales",
"for",
"the",
"aesthetics",
"if",
"none",
"are",
"present"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L213-L256 |
233,421 | has2k1/plotnine | plotnine/scales/scales.py | Scales.add_missing | def add_missing(self, aesthetics):
"""
Add missing but required scales.
Parameters
----------
aesthetics : list | tuple
Aesthetic names. Typically, ('x', 'y').
"""
# Keep only aesthetics that don't have scales
aesthetics = set(aesthetics) - set(self.input())
for ae in aesthetics:
scale_name = 'scale_{}_continuous'.format(ae)
scale_f = Registry[scale_name]
self.append(scale_f()) | python | def add_missing(self, aesthetics):
# Keep only aesthetics that don't have scales
aesthetics = set(aesthetics) - set(self.input())
for ae in aesthetics:
scale_name = 'scale_{}_continuous'.format(ae)
scale_f = Registry[scale_name]
self.append(scale_f()) | [
"def",
"add_missing",
"(",
"self",
",",
"aesthetics",
")",
":",
"# Keep only aesthetics that don't have scales",
"aesthetics",
"=",
"set",
"(",
"aesthetics",
")",
"-",
"set",
"(",
"self",
".",
"input",
"(",
")",
")",
"for",
"ae",
"in",
"aesthetics",
":",
"sc... | Add missing but required scales.
Parameters
----------
aesthetics : list | tuple
Aesthetic names. Typically, ('x', 'y'). | [
"Add",
"missing",
"but",
"required",
"scales",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scales.py#L258-L273 |
233,422 | has2k1/plotnine | plotnine/facets/labelling.py | label_value | def label_value(label_info, multi_line=True):
"""
Convert series values to str and maybe concatenate them
Parameters
----------
label_info : series
Series whose values will be returned
multi_line : bool
Whether to place each variable on a separate line
Returns
-------
out : series
Label text strings
"""
label_info = label_info.astype(str)
if not multi_line:
label_info = collapse_label_lines(label_info)
return label_info | python | def label_value(label_info, multi_line=True):
label_info = label_info.astype(str)
if not multi_line:
label_info = collapse_label_lines(label_info)
return label_info | [
"def",
"label_value",
"(",
"label_info",
",",
"multi_line",
"=",
"True",
")",
":",
"label_info",
"=",
"label_info",
".",
"astype",
"(",
"str",
")",
"if",
"not",
"multi_line",
":",
"label_info",
"=",
"collapse_label_lines",
"(",
"label_info",
")",
"return",
"... | Convert series values to str and maybe concatenate them
Parameters
----------
label_info : series
Series whose values will be returned
multi_line : bool
Whether to place each variable on a separate line
Returns
-------
out : series
Label text strings | [
"Convert",
"series",
"values",
"to",
"str",
"and",
"maybe",
"concatenate",
"them"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/labelling.py#L14-L34 |
233,423 | has2k1/plotnine | plotnine/facets/labelling.py | label_both | def label_both(label_info, multi_line=True, sep=': '):
"""
Concatenate the index and the value of the series.
Parameters
----------
label_info : series
Series whose values will be returned. It must have
an index made of variable names.
multi_line : bool
Whether to place each variable on a separate line
sep : str
Separation between variable name and value
Returns
-------
out : series
Label text strings
"""
label_info = label_info.astype(str)
for var in label_info.index:
label_info[var] = '{0}{1}{2}'.format(var, sep, label_info[var])
if not multi_line:
label_info = collapse_label_lines(label_info)
return label_info | python | def label_both(label_info, multi_line=True, sep=': '):
label_info = label_info.astype(str)
for var in label_info.index:
label_info[var] = '{0}{1}{2}'.format(var, sep, label_info[var])
if not multi_line:
label_info = collapse_label_lines(label_info)
return label_info | [
"def",
"label_both",
"(",
"label_info",
",",
"multi_line",
"=",
"True",
",",
"sep",
"=",
"': '",
")",
":",
"label_info",
"=",
"label_info",
".",
"astype",
"(",
"str",
")",
"for",
"var",
"in",
"label_info",
".",
"index",
":",
"label_info",
"[",
"var",
"... | Concatenate the index and the value of the series.
Parameters
----------
label_info : series
Series whose values will be returned. It must have
an index made of variable names.
multi_line : bool
Whether to place each variable on a separate line
sep : str
Separation between variable name and value
Returns
-------
out : series
Label text strings | [
"Concatenate",
"the",
"index",
"and",
"the",
"value",
"of",
"the",
"series",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/labelling.py#L37-L63 |
233,424 | has2k1/plotnine | plotnine/facets/labelling.py | label_context | def label_context(label_info, multi_line=True, sep=': '):
"""
Create an unabiguous label string
If facetting over a single variable, `label_value` is
used, if two or more variables then `label_both` is used.
Parameters
----------
label_info : series
Series whose values will be returned. It must have
an index made of variable names
multi_line : bool
Whether to place each variable on a separate line
sep : str
Separation between variable name and value
Returns
-------
out : str
Contatenated label values (or pairs of variable names
& values)
"""
if len(label_info) == 1:
return label_value(label_info, multi_line)
else:
return label_both(label_info, multi_line, sep) | python | def label_context(label_info, multi_line=True, sep=': '):
if len(label_info) == 1:
return label_value(label_info, multi_line)
else:
return label_both(label_info, multi_line, sep) | [
"def",
"label_context",
"(",
"label_info",
",",
"multi_line",
"=",
"True",
",",
"sep",
"=",
"': '",
")",
":",
"if",
"len",
"(",
"label_info",
")",
"==",
"1",
":",
"return",
"label_value",
"(",
"label_info",
",",
"multi_line",
")",
"else",
":",
"return",
... | Create an unabiguous label string
If facetting over a single variable, `label_value` is
used, if two or more variables then `label_both` is used.
Parameters
----------
label_info : series
Series whose values will be returned. It must have
an index made of variable names
multi_line : bool
Whether to place each variable on a separate line
sep : str
Separation between variable name and value
Returns
-------
out : str
Contatenated label values (or pairs of variable names
& values) | [
"Create",
"an",
"unabiguous",
"label",
"string"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/labelling.py#L66-L92 |
233,425 | has2k1/plotnine | plotnine/facets/labelling.py | as_labeller | def as_labeller(x, default=label_value, multi_line=True):
"""
Coerse to labeller function
Parameters
----------
x : function | dict
Object to coerce
default : function | str
Default labeller. If it is a string,
it should be the name of one the labelling
functions provided by plotnine.
multi_line : bool
Whether to place each variable on a separate line
Returns
-------
out : function
Labelling function
"""
if x is None:
x = default
# One of the labelling functions as string
with suppress(KeyError, TypeError):
x = LABELLERS[x]
# x is a labeller
with suppress(AttributeError):
if x.__name__ == '_labeller':
return x
def _labeller(label_info):
label_info = pd.Series(label_info).astype(str)
if callable(x) and x.__name__ in LABELLERS:
# labellers in this module
return x(label_info)
elif hasattr(x, '__contains__'):
# dictionary lookup
for var in label_info.index:
if label_info[var] in x:
label_info[var] = x[label_info[var]]
return label_info
elif callable(x):
# generic function
for var in label_info.index:
label_info[var] = x(label_info[var])
return label_info
else:
msg = "Could not use '{0}' for labelling."
raise PlotnineError(msg.format(x))
return _labeller | python | def as_labeller(x, default=label_value, multi_line=True):
if x is None:
x = default
# One of the labelling functions as string
with suppress(KeyError, TypeError):
x = LABELLERS[x]
# x is a labeller
with suppress(AttributeError):
if x.__name__ == '_labeller':
return x
def _labeller(label_info):
label_info = pd.Series(label_info).astype(str)
if callable(x) and x.__name__ in LABELLERS:
# labellers in this module
return x(label_info)
elif hasattr(x, '__contains__'):
# dictionary lookup
for var in label_info.index:
if label_info[var] in x:
label_info[var] = x[label_info[var]]
return label_info
elif callable(x):
# generic function
for var in label_info.index:
label_info[var] = x(label_info[var])
return label_info
else:
msg = "Could not use '{0}' for labelling."
raise PlotnineError(msg.format(x))
return _labeller | [
"def",
"as_labeller",
"(",
"x",
",",
"default",
"=",
"label_value",
",",
"multi_line",
"=",
"True",
")",
":",
"if",
"x",
"is",
"None",
":",
"x",
"=",
"default",
"# One of the labelling functions as string",
"with",
"suppress",
"(",
"KeyError",
",",
"TypeError"... | Coerse to labeller function
Parameters
----------
x : function | dict
Object to coerce
default : function | str
Default labeller. If it is a string,
it should be the name of one the labelling
functions provided by plotnine.
multi_line : bool
Whether to place each variable on a separate line
Returns
-------
out : function
Labelling function | [
"Coerse",
"to",
"labeller",
"function"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/labelling.py#L101-L154 |
233,426 | has2k1/plotnine | plotnine/facets/labelling.py | labeller | def labeller(rows=None, cols=None, multi_line=True,
default=label_value, **kwargs):
"""
Return a labeller function
Parameters
----------
rows : str | function | None
How to label the rows
cols : str | function | None
How to label the columns
multi_line : bool
Whether to place each variable on a separate line
default : function | str
Fallback labelling function. If it is a string,
it should be the name of one the labelling
functions provided by plotnine.
kwargs : dict
{variable name : function | string} pairs for
renaming variables. A function to rename the variable
or a string name.
Returns
-------
out : function
Function to do the labelling
"""
# Sort out the labellers along each dimension
rows_labeller = as_labeller(rows, default, multi_line)
cols_labeller = as_labeller(cols, default, multi_line)
def _labeller(label_info):
# When there is no variable specific labeller,
# use that of the dimension
if label_info._meta['dimension'] == 'rows':
margin_labeller = rows_labeller
else:
margin_labeller = cols_labeller
# Labelling functions expect string values
label_info = label_info.astype(str)
# Each facetting variable is labelled independently
for name, value in label_info.iteritems():
func = as_labeller(kwargs.get(name), margin_labeller)
new_info = func(label_info[[name]])
label_info[name] = new_info[name]
if not multi_line:
label_info = collapse_label_lines(label_info)
return label_info
return _labeller | python | def labeller(rows=None, cols=None, multi_line=True,
default=label_value, **kwargs):
# Sort out the labellers along each dimension
rows_labeller = as_labeller(rows, default, multi_line)
cols_labeller = as_labeller(cols, default, multi_line)
def _labeller(label_info):
# When there is no variable specific labeller,
# use that of the dimension
if label_info._meta['dimension'] == 'rows':
margin_labeller = rows_labeller
else:
margin_labeller = cols_labeller
# Labelling functions expect string values
label_info = label_info.astype(str)
# Each facetting variable is labelled independently
for name, value in label_info.iteritems():
func = as_labeller(kwargs.get(name), margin_labeller)
new_info = func(label_info[[name]])
label_info[name] = new_info[name]
if not multi_line:
label_info = collapse_label_lines(label_info)
return label_info
return _labeller | [
"def",
"labeller",
"(",
"rows",
"=",
"None",
",",
"cols",
"=",
"None",
",",
"multi_line",
"=",
"True",
",",
"default",
"=",
"label_value",
",",
"*",
"*",
"kwargs",
")",
":",
"# Sort out the labellers along each dimension",
"rows_labeller",
"=",
"as_labeller",
... | Return a labeller function
Parameters
----------
rows : str | function | None
How to label the rows
cols : str | function | None
How to label the columns
multi_line : bool
Whether to place each variable on a separate line
default : function | str
Fallback labelling function. If it is a string,
it should be the name of one the labelling
functions provided by plotnine.
kwargs : dict
{variable name : function | string} pairs for
renaming variables. A function to rename the variable
or a string name.
Returns
-------
out : function
Function to do the labelling | [
"Return",
"a",
"labeller",
"function"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/labelling.py#L157-L210 |
233,427 | has2k1/plotnine | plotnine/geoms/geom_violin.py | make_quantile_df | def make_quantile_df(data, draw_quantiles):
"""
Return a dataframe with info needed to draw quantile segments
"""
dens = data['density'].cumsum() / data['density'].sum()
ecdf = interp1d(dens, data['y'], assume_sorted=True)
ys = ecdf(draw_quantiles)
# Get the violin bounds for the requested quantiles
violin_xminvs = interp1d(data['y'], data['xminv'])(ys)
violin_xmaxvs = interp1d(data['y'], data['xmaxv'])(ys)
data = pd.DataFrame({
'x': interleave(violin_xminvs, violin_xmaxvs),
'y': np.repeat(ys, 2),
'group': np.repeat(np.arange(1, len(ys)+1), 2)})
return data | python | def make_quantile_df(data, draw_quantiles):
dens = data['density'].cumsum() / data['density'].sum()
ecdf = interp1d(dens, data['y'], assume_sorted=True)
ys = ecdf(draw_quantiles)
# Get the violin bounds for the requested quantiles
violin_xminvs = interp1d(data['y'], data['xminv'])(ys)
violin_xmaxvs = interp1d(data['y'], data['xmaxv'])(ys)
data = pd.DataFrame({
'x': interleave(violin_xminvs, violin_xmaxvs),
'y': np.repeat(ys, 2),
'group': np.repeat(np.arange(1, len(ys)+1), 2)})
return data | [
"def",
"make_quantile_df",
"(",
"data",
",",
"draw_quantiles",
")",
":",
"dens",
"=",
"data",
"[",
"'density'",
"]",
".",
"cumsum",
"(",
")",
"/",
"data",
"[",
"'density'",
"]",
".",
"sum",
"(",
")",
"ecdf",
"=",
"interp1d",
"(",
"dens",
",",
"data",... | Return a dataframe with info needed to draw quantile segments | [
"Return",
"a",
"dataframe",
"with",
"info",
"needed",
"to",
"draw",
"quantile",
"segments"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/geoms/geom_violin.py#L97-L114 |
233,428 | has2k1/plotnine | plotnine/stats/stat.py | stat.from_geom | def from_geom(geom):
"""
Return an instantiated stat object
stats should not override this method.
Parameters
----------
geom : geom
`geom`
Returns
-------
out : stat
A stat object
Raises
------
:class:`PlotnineError` if unable to create a `stat`.
"""
name = geom.params['stat']
kwargs = geom._kwargs
# More stable when reloading modules than
# using issubclass
if (not isinstance(name, type) and
hasattr(name, 'compute_layer')):
return name
if isinstance(name, stat):
return name
elif isinstance(name, type) and issubclass(name, stat):
klass = name
elif is_string(name):
if not name.startswith('stat_'):
name = 'stat_{}'.format(name)
klass = Registry[name]
else:
raise PlotnineError(
'Unknown stat of type {}'.format(type(name)))
valid_kwargs = (
(klass.aesthetics() |
klass.DEFAULT_PARAMS.keys()) &
kwargs.keys())
params = {k: kwargs[k] for k in valid_kwargs}
return klass(geom=geom, **params) | python | def from_geom(geom):
name = geom.params['stat']
kwargs = geom._kwargs
# More stable when reloading modules than
# using issubclass
if (not isinstance(name, type) and
hasattr(name, 'compute_layer')):
return name
if isinstance(name, stat):
return name
elif isinstance(name, type) and issubclass(name, stat):
klass = name
elif is_string(name):
if not name.startswith('stat_'):
name = 'stat_{}'.format(name)
klass = Registry[name]
else:
raise PlotnineError(
'Unknown stat of type {}'.format(type(name)))
valid_kwargs = (
(klass.aesthetics() |
klass.DEFAULT_PARAMS.keys()) &
kwargs.keys())
params = {k: kwargs[k] for k in valid_kwargs}
return klass(geom=geom, **params) | [
"def",
"from_geom",
"(",
"geom",
")",
":",
"name",
"=",
"geom",
".",
"params",
"[",
"'stat'",
"]",
"kwargs",
"=",
"geom",
".",
"_kwargs",
"# More stable when reloading modules than",
"# using issubclass",
"if",
"(",
"not",
"isinstance",
"(",
"name",
",",
"type... | Return an instantiated stat object
stats should not override this method.
Parameters
----------
geom : geom
`geom`
Returns
-------
out : stat
A stat object
Raises
------
:class:`PlotnineError` if unable to create a `stat`. | [
"Return",
"an",
"instantiated",
"stat",
"object"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/stat.py#L49-L95 |
233,429 | has2k1/plotnine | plotnine/stats/stat.py | stat.aesthetics | def aesthetics(cls):
"""
Return a set of all non-computed aesthetics for this stat.
stats should not override this method.
"""
aesthetics = cls.REQUIRED_AES.copy()
calculated = get_calculated_aes(cls.DEFAULT_AES)
for ae in set(cls.DEFAULT_AES) - set(calculated):
aesthetics.add(ae)
return aesthetics | python | def aesthetics(cls):
aesthetics = cls.REQUIRED_AES.copy()
calculated = get_calculated_aes(cls.DEFAULT_AES)
for ae in set(cls.DEFAULT_AES) - set(calculated):
aesthetics.add(ae)
return aesthetics | [
"def",
"aesthetics",
"(",
"cls",
")",
":",
"aesthetics",
"=",
"cls",
".",
"REQUIRED_AES",
".",
"copy",
"(",
")",
"calculated",
"=",
"get_calculated_aes",
"(",
"cls",
".",
"DEFAULT_AES",
")",
"for",
"ae",
"in",
"set",
"(",
"cls",
".",
"DEFAULT_AES",
")",
... | Return a set of all non-computed aesthetics for this stat.
stats should not override this method. | [
"Return",
"a",
"set",
"of",
"all",
"non",
"-",
"computed",
"aesthetics",
"for",
"this",
"stat",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/stat.py#L118-L128 |
233,430 | has2k1/plotnine | plotnine/stats/stat.py | stat.compute_layer | def compute_layer(cls, data, params, layout):
"""
Calculate statistics for this layers
This is the top-most computation method for the
stat. It does not do any computations, but it
knows how to verify the data, partition it call the
next computation method and merge results.
stats should not override this method.
Parameters
----------
data : panda.DataFrame
Data points for all objects in a layer.
params : dict
Stat parameters
layout : plotnine.layout.Layout
Panel layout information
"""
check_required_aesthetics(
cls.REQUIRED_AES,
list(data.columns) + list(params.keys()),
cls.__name__)
data = remove_missing(
data,
na_rm=params.get('na_rm', False),
vars=list(cls.REQUIRED_AES | cls.NON_MISSING_AES),
name=cls.__name__,
finite=True)
def fn(pdata):
"""
Helper compute function
"""
# Given data belonging to a specific panel, grab
# the corresponding scales and call the method
# that does the real computation
if len(pdata) == 0:
return pdata
pscales = layout.get_scales(pdata['PANEL'].iat[0])
return cls.compute_panel(pdata, pscales, **params)
return groupby_apply(data, 'PANEL', fn) | python | def compute_layer(cls, data, params, layout):
check_required_aesthetics(
cls.REQUIRED_AES,
list(data.columns) + list(params.keys()),
cls.__name__)
data = remove_missing(
data,
na_rm=params.get('na_rm', False),
vars=list(cls.REQUIRED_AES | cls.NON_MISSING_AES),
name=cls.__name__,
finite=True)
def fn(pdata):
"""
Helper compute function
"""
# Given data belonging to a specific panel, grab
# the corresponding scales and call the method
# that does the real computation
if len(pdata) == 0:
return pdata
pscales = layout.get_scales(pdata['PANEL'].iat[0])
return cls.compute_panel(pdata, pscales, **params)
return groupby_apply(data, 'PANEL', fn) | [
"def",
"compute_layer",
"(",
"cls",
",",
"data",
",",
"params",
",",
"layout",
")",
":",
"check_required_aesthetics",
"(",
"cls",
".",
"REQUIRED_AES",
",",
"list",
"(",
"data",
".",
"columns",
")",
"+",
"list",
"(",
"params",
".",
"keys",
"(",
")",
")"... | Calculate statistics for this layers
This is the top-most computation method for the
stat. It does not do any computations, but it
knows how to verify the data, partition it call the
next computation method and merge results.
stats should not override this method.
Parameters
----------
data : panda.DataFrame
Data points for all objects in a layer.
params : dict
Stat parameters
layout : plotnine.layout.Layout
Panel layout information | [
"Calculate",
"statistics",
"for",
"this",
"layers"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/stat.py#L223-L267 |
233,431 | has2k1/plotnine | plotnine/stats/stat.py | stat.compute_panel | def compute_panel(cls, data, scales, **params):
"""
Calculate the stats of all the groups and
return the results in a single dataframe.
This is a default function that can be overriden
by individual stats
Parameters
----------
data : dataframe
data for the computing
scales : types.SimpleNamespace
x (``scales.x``) and y (``scales.y``) scale objects.
The most likely reason to use scale information is
to find out the physical size of a scale. e.g::
range_x = scales.x.dimension()
params : dict
The parameters for the stat. It includes default
values if user did not set a particular parameter.
"""
if not len(data):
return type(data)()
stats = []
for _, old in data.groupby('group'):
new = cls.compute_group(old, scales, **params)
unique = uniquecols(old)
missing = unique.columns.difference(new.columns)
u = unique.loc[[0]*len(new), missing].reset_index(drop=True)
# concat can have problems with empty dataframes that
# have an index
if u.empty and len(u):
u = type(data)()
df = pd.concat([new, u], axis=1)
stats.append(df)
stats = pd.concat(stats, axis=0, ignore_index=True)
# Note: If the data coming in has columns with non-unique
# values with-in group(s), this implementation loses the
# columns. Individual stats may want to do some preparation
# before then fall back on this implementation or override
# it completely.
return stats | python | def compute_panel(cls, data, scales, **params):
if not len(data):
return type(data)()
stats = []
for _, old in data.groupby('group'):
new = cls.compute_group(old, scales, **params)
unique = uniquecols(old)
missing = unique.columns.difference(new.columns)
u = unique.loc[[0]*len(new), missing].reset_index(drop=True)
# concat can have problems with empty dataframes that
# have an index
if u.empty and len(u):
u = type(data)()
df = pd.concat([new, u], axis=1)
stats.append(df)
stats = pd.concat(stats, axis=0, ignore_index=True)
# Note: If the data coming in has columns with non-unique
# values with-in group(s), this implementation loses the
# columns. Individual stats may want to do some preparation
# before then fall back on this implementation or override
# it completely.
return stats | [
"def",
"compute_panel",
"(",
"cls",
",",
"data",
",",
"scales",
",",
"*",
"*",
"params",
")",
":",
"if",
"not",
"len",
"(",
"data",
")",
":",
"return",
"type",
"(",
"data",
")",
"(",
")",
"stats",
"=",
"[",
"]",
"for",
"_",
",",
"old",
"in",
... | Calculate the stats of all the groups and
return the results in a single dataframe.
This is a default function that can be overriden
by individual stats
Parameters
----------
data : dataframe
data for the computing
scales : types.SimpleNamespace
x (``scales.x``) and y (``scales.y``) scale objects.
The most likely reason to use scale information is
to find out the physical size of a scale. e.g::
range_x = scales.x.dimension()
params : dict
The parameters for the stat. It includes default
values if user did not set a particular parameter. | [
"Calculate",
"the",
"stats",
"of",
"all",
"the",
"groups",
"and",
"return",
"the",
"results",
"in",
"a",
"single",
"dataframe",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/stat.py#L270-L317 |
233,432 | has2k1/plotnine | plotnine/stats/density.py | kde_scipy | def kde_scipy(data, grid, **kwargs):
"""
Kernel Density Estimation with Scipy
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions
"""
kde = gaussian_kde(data.T, **kwargs)
return kde.evaluate(grid.T) | python | def kde_scipy(data, grid, **kwargs):
kde = gaussian_kde(data.T, **kwargs)
return kde.evaluate(grid.T) | [
"def",
"kde_scipy",
"(",
"data",
",",
"grid",
",",
"*",
"*",
"kwargs",
")",
":",
"kde",
"=",
"gaussian_kde",
"(",
"data",
".",
"T",
",",
"*",
"*",
"kwargs",
")",
"return",
"kde",
".",
"evaluate",
"(",
"grid",
".",
"T",
")"
] | Kernel Density Estimation with Scipy
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions | [
"Kernel",
"Density",
"Estimation",
"with",
"Scipy"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/density.py#L23-L44 |
233,433 | has2k1/plotnine | plotnine/stats/density.py | kde_statsmodels_u | def kde_statsmodels_u(data, grid, **kwargs):
"""
Univariate Kernel Density Estimation with Statsmodels
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x 1` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x 1` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions
"""
kde = KDEUnivariate(data)
kde.fit(**kwargs)
return kde.evaluate(grid) | python | def kde_statsmodels_u(data, grid, **kwargs):
kde = KDEUnivariate(data)
kde.fit(**kwargs)
return kde.evaluate(grid) | [
"def",
"kde_statsmodels_u",
"(",
"data",
",",
"grid",
",",
"*",
"*",
"kwargs",
")",
":",
"kde",
"=",
"KDEUnivariate",
"(",
"data",
")",
"kde",
".",
"fit",
"(",
"*",
"*",
"kwargs",
")",
"return",
"kde",
".",
"evaluate",
"(",
"grid",
")"
] | Univariate Kernel Density Estimation with Statsmodels
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x 1` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x 1` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions | [
"Univariate",
"Kernel",
"Density",
"Estimation",
"with",
"Statsmodels"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/density.py#L47-L69 |
233,434 | has2k1/plotnine | plotnine/stats/density.py | kde_statsmodels_m | def kde_statsmodels_m(data, grid, **kwargs):
"""
Multivariate Kernel Density Estimation with Statsmodels
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions
"""
kde = KDEMultivariate(data, **kwargs)
return kde.pdf(grid) | python | def kde_statsmodels_m(data, grid, **kwargs):
kde = KDEMultivariate(data, **kwargs)
return kde.pdf(grid) | [
"def",
"kde_statsmodels_m",
"(",
"data",
",",
"grid",
",",
"*",
"*",
"kwargs",
")",
":",
"kde",
"=",
"KDEMultivariate",
"(",
"data",
",",
"*",
"*",
"kwargs",
")",
"return",
"kde",
".",
"pdf",
"(",
"grid",
")"
] | Multivariate Kernel Density Estimation with Statsmodels
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions | [
"Multivariate",
"Kernel",
"Density",
"Estimation",
"with",
"Statsmodels"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/density.py#L72-L93 |
233,435 | has2k1/plotnine | plotnine/stats/density.py | kde_sklearn | def kde_sklearn(data, grid, **kwargs):
"""
Kernel Density Estimation with Scikit-learn
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions
"""
kde_skl = KernelDensity(**kwargs)
kde_skl.fit(data)
# score_samples() returns the log-likelihood of the samples
log_pdf = kde_skl.score_samples(grid)
return np.exp(log_pdf) | python | def kde_sklearn(data, grid, **kwargs):
kde_skl = KernelDensity(**kwargs)
kde_skl.fit(data)
# score_samples() returns the log-likelihood of the samples
log_pdf = kde_skl.score_samples(grid)
return np.exp(log_pdf) | [
"def",
"kde_sklearn",
"(",
"data",
",",
"grid",
",",
"*",
"*",
"kwargs",
")",
":",
"kde_skl",
"=",
"KernelDensity",
"(",
"*",
"*",
"kwargs",
")",
"kde_skl",
".",
"fit",
"(",
"data",
")",
"# score_samples() returns the log-likelihood of the samples",
"log_pdf",
... | Kernel Density Estimation with Scikit-learn
Parameters
----------
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions | [
"Kernel",
"Density",
"Estimation",
"with",
"Scikit",
"-",
"learn"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/density.py#L96-L120 |
233,436 | has2k1/plotnine | plotnine/stats/density.py | kde | def kde(data, grid, package, **kwargs):
"""
Kernel Density Estimation
Parameters
----------
package : str
Package whose kernel density estimation to use.
Should be one of
`['statsmodels-u', 'statsmodels-m', 'scipy', 'sklearn']`.
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions
"""
if package == 'statsmodels':
package = 'statsmodels-m'
func = KDE_FUNCS[package]
return func(data, grid, **kwargs) | python | def kde(data, grid, package, **kwargs):
if package == 'statsmodels':
package = 'statsmodels-m'
func = KDE_FUNCS[package]
return func(data, grid, **kwargs) | [
"def",
"kde",
"(",
"data",
",",
"grid",
",",
"package",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"package",
"==",
"'statsmodels'",
":",
"package",
"=",
"'statsmodels-m'",
"func",
"=",
"KDE_FUNCS",
"[",
"package",
"]",
"return",
"func",
"(",
"data",
","... | Kernel Density Estimation
Parameters
----------
package : str
Package whose kernel density estimation to use.
Should be one of
`['statsmodels-u', 'statsmodels-m', 'scipy', 'sklearn']`.
data : numpy.array
Data points used to compute a density estimator. It
has `n x p` dimensions, representing n points and p
variables.
grid : numpy.array
Data points at which the desity will be estimated. It
has `m x p` dimensions, representing m points and p
variables.
Returns
-------
out : numpy.array
Density estimate. Has `m x 1` dimensions | [
"Kernel",
"Density",
"Estimation"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/density.py#L132-L159 |
233,437 | has2k1/plotnine | plotnine/positions/position_dodge.py | position_dodge.strategy | def strategy(data, params):
"""
Dodge overlapping interval
Assumes that each set has the same horizontal position.
"""
width = params['width']
with suppress(TypeError):
iter(width)
width = np.asarray(width)
width = width[data.index]
udata_group = data['group'].drop_duplicates()
n = params.get('n', None)
if n is None:
n = len(udata_group)
if n == 1:
return data
if not all([col in data.columns for col in ['xmin', 'xmax']]):
data['xmin'] = data['x']
data['xmax'] = data['x']
d_width = np.max(data['xmax'] - data['xmin'])
# Have a new group index from 1 to number of groups.
# This might be needed if the group numbers in this set don't
# include all of 1:n
udata_group = udata_group.sort_values()
groupidx = match(data['group'], udata_group)
groupidx = np.asarray(groupidx) + 1
# Find the center for each group, then use that to
# calculate xmin and xmax
data['x'] = data['x'] + width * ((groupidx - 0.5) / n - 0.5)
data['xmin'] = data['x'] - (d_width / n) / 2
data['xmax'] = data['x'] + (d_width / n) / 2
return data | python | def strategy(data, params):
width = params['width']
with suppress(TypeError):
iter(width)
width = np.asarray(width)
width = width[data.index]
udata_group = data['group'].drop_duplicates()
n = params.get('n', None)
if n is None:
n = len(udata_group)
if n == 1:
return data
if not all([col in data.columns for col in ['xmin', 'xmax']]):
data['xmin'] = data['x']
data['xmax'] = data['x']
d_width = np.max(data['xmax'] - data['xmin'])
# Have a new group index from 1 to number of groups.
# This might be needed if the group numbers in this set don't
# include all of 1:n
udata_group = udata_group.sort_values()
groupidx = match(data['group'], udata_group)
groupidx = np.asarray(groupidx) + 1
# Find the center for each group, then use that to
# calculate xmin and xmax
data['x'] = data['x'] + width * ((groupidx - 0.5) / n - 0.5)
data['xmin'] = data['x'] - (d_width / n) / 2
data['xmax'] = data['x'] + (d_width / n) / 2
return data | [
"def",
"strategy",
"(",
"data",
",",
"params",
")",
":",
"width",
"=",
"params",
"[",
"'width'",
"]",
"with",
"suppress",
"(",
"TypeError",
")",
":",
"iter",
"(",
"width",
")",
"width",
"=",
"np",
".",
"asarray",
"(",
"width",
")",
"width",
"=",
"w... | Dodge overlapping interval
Assumes that each set has the same horizontal position. | [
"Dodge",
"overlapping",
"interval"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/positions/position_dodge.py#L59-L98 |
233,438 | has2k1/plotnine | plotnine/facets/facet_grid.py | parse_grid_facets | def parse_grid_facets(facets):
"""
Return two lists of facetting variables, for the rows & columns
"""
valid_seqs = ["('var1', '.')", "('var1', 'var2')",
"('.', 'var1')", "((var1, var2), (var3, var4))"]
error_msg_s = ("Valid sequences for specifying 'facets' look like"
" {}".format(valid_seqs))
valid_forms = ['var1 ~ .', 'var1 ~ var2', '. ~ var1',
'var1 + var2 ~ var3 + var4',
'. ~ func(var1) + func(var2)',
'. ~ func(var1+var3) + func(var2)'
] + valid_seqs
error_msg_f = ("Valid formula for 'facet_grid' look like"
" {}".format(valid_forms))
if isinstance(facets, (tuple, list)):
if len(facets) != 2:
raise PlotnineError(error_msg_s)
rows, cols = facets
if isinstance(rows, str):
rows = [] if rows == '.' else [rows]
if isinstance(cols, str):
cols = [] if cols == '.' else [cols]
return rows, cols
if not isinstance(facets, str):
raise PlotnineError(error_msg_f)
# Example of allowed formulae
# 'c ~ a + b'
# '. ~ func(a) + func(b)'
# 'func(c) ~ func(a+1) + func(b+2)'
try:
lhs, rhs = facets.split('~')
except ValueError:
raise PlotnineError(error_msg_s)
else:
lhs = lhs.strip()
rhs = rhs.strip()
lhs = ensure_var_or_dot(lhs)
rhs = ensure_var_or_dot(rhs)
lsplitter = ' + ' if ' + ' in lhs else '+'
rsplitter = ' + ' if ' + ' in rhs else '+'
if lhs == '.':
rows = []
else:
rows = [var.strip() for var in lhs.split(lsplitter)]
if rhs == '.':
cols = []
else:
cols = [var.strip() for var in rhs.split(rsplitter)]
return rows, cols | python | def parse_grid_facets(facets):
valid_seqs = ["('var1', '.')", "('var1', 'var2')",
"('.', 'var1')", "((var1, var2), (var3, var4))"]
error_msg_s = ("Valid sequences for specifying 'facets' look like"
" {}".format(valid_seqs))
valid_forms = ['var1 ~ .', 'var1 ~ var2', '. ~ var1',
'var1 + var2 ~ var3 + var4',
'. ~ func(var1) + func(var2)',
'. ~ func(var1+var3) + func(var2)'
] + valid_seqs
error_msg_f = ("Valid formula for 'facet_grid' look like"
" {}".format(valid_forms))
if isinstance(facets, (tuple, list)):
if len(facets) != 2:
raise PlotnineError(error_msg_s)
rows, cols = facets
if isinstance(rows, str):
rows = [] if rows == '.' else [rows]
if isinstance(cols, str):
cols = [] if cols == '.' else [cols]
return rows, cols
if not isinstance(facets, str):
raise PlotnineError(error_msg_f)
# Example of allowed formulae
# 'c ~ a + b'
# '. ~ func(a) + func(b)'
# 'func(c) ~ func(a+1) + func(b+2)'
try:
lhs, rhs = facets.split('~')
except ValueError:
raise PlotnineError(error_msg_s)
else:
lhs = lhs.strip()
rhs = rhs.strip()
lhs = ensure_var_or_dot(lhs)
rhs = ensure_var_or_dot(rhs)
lsplitter = ' + ' if ' + ' in lhs else '+'
rsplitter = ' + ' if ' + ' in rhs else '+'
if lhs == '.':
rows = []
else:
rows = [var.strip() for var in lhs.split(lsplitter)]
if rhs == '.':
cols = []
else:
cols = [var.strip() for var in rhs.split(rsplitter)]
return rows, cols | [
"def",
"parse_grid_facets",
"(",
"facets",
")",
":",
"valid_seqs",
"=",
"[",
"\"('var1', '.')\"",
",",
"\"('var1', 'var2')\"",
",",
"\"('.', 'var1')\"",
",",
"\"((var1, var2), (var3, var4))\"",
"]",
"error_msg_s",
"=",
"(",
"\"Valid sequences for specifying 'facets' look like... | Return two lists of facetting variables, for the rows & columns | [
"Return",
"two",
"lists",
"of",
"facetting",
"variables",
"for",
"the",
"rows",
"&",
"columns"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet_grid.py#L254-L315 |
233,439 | has2k1/plotnine | plotnine/coords/coord.py | coord.expand_default | def expand_default(self, scale, discrete=(0, 0.6, 0, 0.6),
continuous=(0.05, 0, 0.05, 0)):
"""
Expand a single scale
"""
if is_waive(scale.expand):
if isinstance(scale, scale_discrete):
return discrete
elif isinstance(scale, scale_continuous):
return continuous
else:
name = scale.__class__.__name__
msg = "Failed to expand scale '{}'".format(name)
raise PlotnineError(msg)
else:
return scale.expand | python | def expand_default(self, scale, discrete=(0, 0.6, 0, 0.6),
continuous=(0.05, 0, 0.05, 0)):
if is_waive(scale.expand):
if isinstance(scale, scale_discrete):
return discrete
elif isinstance(scale, scale_continuous):
return continuous
else:
name = scale.__class__.__name__
msg = "Failed to expand scale '{}'".format(name)
raise PlotnineError(msg)
else:
return scale.expand | [
"def",
"expand_default",
"(",
"self",
",",
"scale",
",",
"discrete",
"=",
"(",
"0",
",",
"0.6",
",",
"0",
",",
"0.6",
")",
",",
"continuous",
"=",
"(",
"0.05",
",",
"0",
",",
"0.05",
",",
"0",
")",
")",
":",
"if",
"is_waive",
"(",
"scale",
".",... | Expand a single scale | [
"Expand",
"a",
"single",
"scale"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/coords/coord.py#L113-L128 |
233,440 | has2k1/plotnine | plotnine/doctools.py | dict_to_table | def dict_to_table(header, contents):
"""
Convert dict to table
Parameters
----------
header : tuple
Table header. Should have a length of 2.
contents : dict
The key becomes column 1 of table and the
value becomes column 2 of table.
"""
def to_text(row):
name, value = row
m = max_col1_size + 1 - len(name)
spacing = ' ' * m
return ''.join([name, spacing, value])
thead = tuple(str(col) for col in header)
rows = []
for name, value in contents.items():
# code highlighting
if value != '':
if isinstance(value, str):
value = "'{}'".format(value)
value = ':py:`{}`'.format(value)
rows.append((name, value))
n = np.max([len(header[0])] +
[len(col1) for col1, _ in rows])
hborder = tuple('='*n for col in header)
rows = [hborder, thead, hborder] + rows + [hborder]
max_col1_size = np.max([len(col1) for col1, _ in rows])
table = '\n'.join([to_text(row) for row in rows])
return table | python | def dict_to_table(header, contents):
def to_text(row):
name, value = row
m = max_col1_size + 1 - len(name)
spacing = ' ' * m
return ''.join([name, spacing, value])
thead = tuple(str(col) for col in header)
rows = []
for name, value in contents.items():
# code highlighting
if value != '':
if isinstance(value, str):
value = "'{}'".format(value)
value = ':py:`{}`'.format(value)
rows.append((name, value))
n = np.max([len(header[0])] +
[len(col1) for col1, _ in rows])
hborder = tuple('='*n for col in header)
rows = [hborder, thead, hborder] + rows + [hborder]
max_col1_size = np.max([len(col1) for col1, _ in rows])
table = '\n'.join([to_text(row) for row in rows])
return table | [
"def",
"dict_to_table",
"(",
"header",
",",
"contents",
")",
":",
"def",
"to_text",
"(",
"row",
")",
":",
"name",
",",
"value",
"=",
"row",
"m",
"=",
"max_col1_size",
"+",
"1",
"-",
"len",
"(",
"name",
")",
"spacing",
"=",
"' '",
"*",
"m",
"return"... | Convert dict to table
Parameters
----------
header : tuple
Table header. Should have a length of 2.
contents : dict
The key becomes column 1 of table and the
value becomes column 2 of table. | [
"Convert",
"dict",
"to",
"table"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L128-L163 |
233,441 | has2k1/plotnine | plotnine/doctools.py | make_signature | def make_signature(name, params, common_params, common_param_values):
"""
Create a signature for a geom or stat
Gets the DEFAULT_PARAMS (params) and creates are comma
separated list of the `name=value` pairs. The common_params
come first in the list, and they get take their values from
either the params-dict or the common_geom_param_values-dict.
"""
tokens = []
seen = set()
def tokens_append(key, value):
if isinstance(value, str):
value = "'{}'".format(value)
tokens.append('{}={}'.format(key, value))
# preferred params come first
for key in common_params:
seen.add(key)
try:
value = params[key]
except KeyError:
value = common_param_values[key]
tokens_append(key, value)
# other params (these are the geom/stat specific parameters
for key in (set(params) - seen):
tokens_append(key, params[key])
# name, 1 opening bracket, 4 spaces in SIGNATURE_TPL
s1 = name + '('
s2 = ', '.join(tokens) + ', **kwargs)'
line_width = 78 - len(s1)
indent_spaces = ' ' * (len(s1) + 4)
newline_and_space = '\n' + indent_spaces
s2_lines = wrap(s2, width=line_width)
return s1 + newline_and_space.join(s2_lines) | python | def make_signature(name, params, common_params, common_param_values):
tokens = []
seen = set()
def tokens_append(key, value):
if isinstance(value, str):
value = "'{}'".format(value)
tokens.append('{}={}'.format(key, value))
# preferred params come first
for key in common_params:
seen.add(key)
try:
value = params[key]
except KeyError:
value = common_param_values[key]
tokens_append(key, value)
# other params (these are the geom/stat specific parameters
for key in (set(params) - seen):
tokens_append(key, params[key])
# name, 1 opening bracket, 4 spaces in SIGNATURE_TPL
s1 = name + '('
s2 = ', '.join(tokens) + ', **kwargs)'
line_width = 78 - len(s1)
indent_spaces = ' ' * (len(s1) + 4)
newline_and_space = '\n' + indent_spaces
s2_lines = wrap(s2, width=line_width)
return s1 + newline_and_space.join(s2_lines) | [
"def",
"make_signature",
"(",
"name",
",",
"params",
",",
"common_params",
",",
"common_param_values",
")",
":",
"tokens",
"=",
"[",
"]",
"seen",
"=",
"set",
"(",
")",
"def",
"tokens_append",
"(",
"key",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
... | Create a signature for a geom or stat
Gets the DEFAULT_PARAMS (params) and creates are comma
separated list of the `name=value` pairs. The common_params
come first in the list, and they get take their values from
either the params-dict or the common_geom_param_values-dict. | [
"Create",
"a",
"signature",
"for",
"a",
"geom",
"or",
"stat"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L166-L203 |
233,442 | has2k1/plotnine | plotnine/doctools.py | docstring_section_lines | def docstring_section_lines(docstring, section_name):
"""
Return a section of a numpydoc string
Paramters
---------
docstring : str
Docstring
section_name : str
Name of section to return
Returns
-------
section : str
Section minus the header
"""
lines = []
inside_section = False
underline = '-' * len(section_name)
expect_underline = False
for line in docstring.splitlines():
_line = line.strip().lower()
if expect_underline:
expect_underline = False
if _line == underline:
inside_section = True
continue
if _line == section_name:
expect_underline = True
elif _line in DOCSTRING_SECTIONS:
# next section
break
elif inside_section:
lines.append(line)
return '\n'.join(lines) | python | def docstring_section_lines(docstring, section_name):
lines = []
inside_section = False
underline = '-' * len(section_name)
expect_underline = False
for line in docstring.splitlines():
_line = line.strip().lower()
if expect_underline:
expect_underline = False
if _line == underline:
inside_section = True
continue
if _line == section_name:
expect_underline = True
elif _line in DOCSTRING_SECTIONS:
# next section
break
elif inside_section:
lines.append(line)
return '\n'.join(lines) | [
"def",
"docstring_section_lines",
"(",
"docstring",
",",
"section_name",
")",
":",
"lines",
"=",
"[",
"]",
"inside_section",
"=",
"False",
"underline",
"=",
"'-'",
"*",
"len",
"(",
"section_name",
")",
"expect_underline",
"=",
"False",
"for",
"line",
"in",
"... | Return a section of a numpydoc string
Paramters
---------
docstring : str
Docstring
section_name : str
Name of section to return
Returns
-------
section : str
Section minus the header | [
"Return",
"a",
"section",
"of",
"a",
"numpydoc",
"string"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L207-L243 |
233,443 | has2k1/plotnine | plotnine/doctools.py | parameters_str_to_dict | def parameters_str_to_dict(param_section):
"""
Convert a param section to a dict
Parameters
----------
param_section : str
Text in the parameter section
Returns
-------
d : OrderedDict
Dictionary of the parameters in the order that they
are described in the parameters section. The dict
is of the form ``{param: all_parameter_text}``.
You can reconstruct the ``param_section`` from the
keys of the dictionary.
See Also
--------
:func:`parameters_dict_to_str`
"""
d = OrderedDict()
previous_param = None
param_desc = None
for line in param_section.split('\n'):
param = param_spec(line)
if param:
if previous_param:
d[previous_param] = '\n'.join(param_desc)
param_desc = [line]
previous_param = param
elif param_desc:
param_desc.append(line)
if previous_param:
d[previous_param] = '\n'.join(param_desc)
return d | python | def parameters_str_to_dict(param_section):
d = OrderedDict()
previous_param = None
param_desc = None
for line in param_section.split('\n'):
param = param_spec(line)
if param:
if previous_param:
d[previous_param] = '\n'.join(param_desc)
param_desc = [line]
previous_param = param
elif param_desc:
param_desc.append(line)
if previous_param:
d[previous_param] = '\n'.join(param_desc)
return d | [
"def",
"parameters_str_to_dict",
"(",
"param_section",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"previous_param",
"=",
"None",
"param_desc",
"=",
"None",
"for",
"line",
"in",
"param_section",
".",
"split",
"(",
"'\\n'",
")",
":",
"param",
"=",
"param_spe... | Convert a param section to a dict
Parameters
----------
param_section : str
Text in the parameter section
Returns
-------
d : OrderedDict
Dictionary of the parameters in the order that they
are described in the parameters section. The dict
is of the form ``{param: all_parameter_text}``.
You can reconstruct the ``param_section`` from the
keys of the dictionary.
See Also
--------
:func:`parameters_dict_to_str` | [
"Convert",
"a",
"param",
"section",
"to",
"a",
"dict"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L279-L317 |
233,444 | has2k1/plotnine | plotnine/doctools.py | document_geom | def document_geom(geom):
"""
Create a structured documentation for the geom
It replaces `{usage}`, `{common_parameters}` and
`{aesthetics}` with generated documentation.
"""
# Dedented so that it lineups (in sphinx) with the part
# generated parts when put together
docstring = dedent(geom.__doc__)
# usage
signature = make_signature(geom.__name__,
geom.DEFAULT_PARAMS,
common_geom_params,
common_geom_param_values)
usage = GEOM_SIGNATURE_TPL.format(signature=signature)
# aesthetics
contents = OrderedDict(('**{}**'.format(ae), '')
for ae in sorted(geom.REQUIRED_AES))
if geom.DEFAULT_AES:
d = geom.DEFAULT_AES.copy()
d['group'] = '' # All geoms understand the group aesthetic
contents.update(sorted(d.items()))
table = dict_to_table(('Aesthetic', 'Default value'), contents)
aesthetics_table = AESTHETICS_TABLE_TPL.format(table=table)
tpl = dedent(geom._aesthetics_doc.lstrip('\n'))
aesthetics_doc = tpl.format(aesthetics_table=aesthetics_table)
aesthetics_doc = indent(aesthetics_doc, ' '*4)
# common_parameters
d = geom.DEFAULT_PARAMS
common_parameters = GEOM_PARAMS_TPL.format(
default_stat=d['stat'],
default_position=d['position'],
default_na_rm=d['na_rm'],
default_inherit_aes=d.get('inherit_aes', True),
_aesthetics_doc=aesthetics_doc,
**common_params_doc)
docstring = docstring.replace('{usage}', usage)
docstring = docstring.replace('{common_parameters}',
common_parameters)
geom.__doc__ = docstring
return geom | python | def document_geom(geom):
# Dedented so that it lineups (in sphinx) with the part
# generated parts when put together
docstring = dedent(geom.__doc__)
# usage
signature = make_signature(geom.__name__,
geom.DEFAULT_PARAMS,
common_geom_params,
common_geom_param_values)
usage = GEOM_SIGNATURE_TPL.format(signature=signature)
# aesthetics
contents = OrderedDict(('**{}**'.format(ae), '')
for ae in sorted(geom.REQUIRED_AES))
if geom.DEFAULT_AES:
d = geom.DEFAULT_AES.copy()
d['group'] = '' # All geoms understand the group aesthetic
contents.update(sorted(d.items()))
table = dict_to_table(('Aesthetic', 'Default value'), contents)
aesthetics_table = AESTHETICS_TABLE_TPL.format(table=table)
tpl = dedent(geom._aesthetics_doc.lstrip('\n'))
aesthetics_doc = tpl.format(aesthetics_table=aesthetics_table)
aesthetics_doc = indent(aesthetics_doc, ' '*4)
# common_parameters
d = geom.DEFAULT_PARAMS
common_parameters = GEOM_PARAMS_TPL.format(
default_stat=d['stat'],
default_position=d['position'],
default_na_rm=d['na_rm'],
default_inherit_aes=d.get('inherit_aes', True),
_aesthetics_doc=aesthetics_doc,
**common_params_doc)
docstring = docstring.replace('{usage}', usage)
docstring = docstring.replace('{common_parameters}',
common_parameters)
geom.__doc__ = docstring
return geom | [
"def",
"document_geom",
"(",
"geom",
")",
":",
"# Dedented so that it lineups (in sphinx) with the part",
"# generated parts when put together",
"docstring",
"=",
"dedent",
"(",
"geom",
".",
"__doc__",
")",
"# usage",
"signature",
"=",
"make_signature",
"(",
"geom",
".",
... | Create a structured documentation for the geom
It replaces `{usage}`, `{common_parameters}` and
`{aesthetics}` with generated documentation. | [
"Create",
"a",
"structured",
"documentation",
"for",
"the",
"geom"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L341-L387 |
233,445 | has2k1/plotnine | plotnine/doctools.py | document_stat | def document_stat(stat):
"""
Create a structured documentation for the stat
It replaces `{usage}`, `{common_parameters}` and
`{aesthetics}` with generated documentation.
"""
# Dedented so that it lineups (in sphinx) with the part
# generated parts when put together
docstring = dedent(stat.__doc__)
# usage:
signature = make_signature(stat.__name__,
stat.DEFAULT_PARAMS,
common_stat_params,
common_stat_param_values)
usage = STAT_SIGNATURE_TPL.format(signature=signature)
# aesthetics
contents = OrderedDict(('**{}**'.format(ae), '')
for ae in sorted(stat.REQUIRED_AES))
contents.update(sorted(stat.DEFAULT_AES.items()))
table = dict_to_table(('Aesthetic', 'Default value'), contents)
aesthetics_table = AESTHETICS_TABLE_TPL.format(table=table)
tpl = dedent(stat._aesthetics_doc.lstrip('\n'))
aesthetics_doc = tpl.format(aesthetics_table=aesthetics_table)
aesthetics_doc = indent(aesthetics_doc, ' '*4)
# common_parameters
d = stat.DEFAULT_PARAMS
common_parameters = STAT_PARAMS_TPL.format(
default_geom=d['geom'],
default_position=d['position'],
default_na_rm=d['na_rm'],
_aesthetics_doc=aesthetics_doc,
**common_params_doc)
docstring = docstring.replace('{usage}', usage)
docstring = docstring.replace('{common_parameters}',
common_parameters)
stat.__doc__ = docstring
return stat | python | def document_stat(stat):
# Dedented so that it lineups (in sphinx) with the part
# generated parts when put together
docstring = dedent(stat.__doc__)
# usage:
signature = make_signature(stat.__name__,
stat.DEFAULT_PARAMS,
common_stat_params,
common_stat_param_values)
usage = STAT_SIGNATURE_TPL.format(signature=signature)
# aesthetics
contents = OrderedDict(('**{}**'.format(ae), '')
for ae in sorted(stat.REQUIRED_AES))
contents.update(sorted(stat.DEFAULT_AES.items()))
table = dict_to_table(('Aesthetic', 'Default value'), contents)
aesthetics_table = AESTHETICS_TABLE_TPL.format(table=table)
tpl = dedent(stat._aesthetics_doc.lstrip('\n'))
aesthetics_doc = tpl.format(aesthetics_table=aesthetics_table)
aesthetics_doc = indent(aesthetics_doc, ' '*4)
# common_parameters
d = stat.DEFAULT_PARAMS
common_parameters = STAT_PARAMS_TPL.format(
default_geom=d['geom'],
default_position=d['position'],
default_na_rm=d['na_rm'],
_aesthetics_doc=aesthetics_doc,
**common_params_doc)
docstring = docstring.replace('{usage}', usage)
docstring = docstring.replace('{common_parameters}',
common_parameters)
stat.__doc__ = docstring
return stat | [
"def",
"document_stat",
"(",
"stat",
")",
":",
"# Dedented so that it lineups (in sphinx) with the part",
"# generated parts when put together",
"docstring",
"=",
"dedent",
"(",
"stat",
".",
"__doc__",
")",
"# usage:",
"signature",
"=",
"make_signature",
"(",
"stat",
".",... | Create a structured documentation for the stat
It replaces `{usage}`, `{common_parameters}` and
`{aesthetics}` with generated documentation. | [
"Create",
"a",
"structured",
"documentation",
"for",
"the",
"stat"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L390-L431 |
233,446 | has2k1/plotnine | plotnine/doctools.py | document_scale | def document_scale(cls):
"""
Create a documentation for a scale
Import the superclass parameters
It replaces `{superclass_parameters}` with the documentation
of the parameters from the superclass.
Parameters
----------
cls : type
A scale class
Returns
-------
cls : type
The scale class with a modified docstring.
"""
params_list = []
# Get set of cls params
cls_param_string = docstring_parameters_section(cls)
cls_param_dict = parameters_str_to_dict(cls_param_string)
cls_params = set(cls_param_dict.keys())
for i, base in enumerate(cls.__bases__):
# Get set of base class params
base_param_string = param_string = docstring_parameters_section(base)
base_param_dict = parameters_str_to_dict(base_param_string)
base_params = set(base_param_dict.keys())
# Remove duplicate params from the base class
duplicate_params = base_params & cls_params
for param in duplicate_params:
del base_param_dict[param]
if duplicate_params:
param_string = parameters_dict_to_str(base_param_dict)
# Accumulate params of base case
if i == 0:
# Compensate for the indentation of the
# {superclass_parameters} string
param_string = param_string.strip()
params_list.append(param_string)
# Prevent the next base classes from bringing in the
# same parameters.
cls_params |= base_params
# Fill in the processed superclass parameters
superclass_parameters = '\n'.join(params_list)
cls.__doc__ = cls.__doc__.format(
superclass_parameters=superclass_parameters)
return cls | python | def document_scale(cls):
params_list = []
# Get set of cls params
cls_param_string = docstring_parameters_section(cls)
cls_param_dict = parameters_str_to_dict(cls_param_string)
cls_params = set(cls_param_dict.keys())
for i, base in enumerate(cls.__bases__):
# Get set of base class params
base_param_string = param_string = docstring_parameters_section(base)
base_param_dict = parameters_str_to_dict(base_param_string)
base_params = set(base_param_dict.keys())
# Remove duplicate params from the base class
duplicate_params = base_params & cls_params
for param in duplicate_params:
del base_param_dict[param]
if duplicate_params:
param_string = parameters_dict_to_str(base_param_dict)
# Accumulate params of base case
if i == 0:
# Compensate for the indentation of the
# {superclass_parameters} string
param_string = param_string.strip()
params_list.append(param_string)
# Prevent the next base classes from bringing in the
# same parameters.
cls_params |= base_params
# Fill in the processed superclass parameters
superclass_parameters = '\n'.join(params_list)
cls.__doc__ = cls.__doc__.format(
superclass_parameters=superclass_parameters)
return cls | [
"def",
"document_scale",
"(",
"cls",
")",
":",
"params_list",
"=",
"[",
"]",
"# Get set of cls params",
"cls_param_string",
"=",
"docstring_parameters_section",
"(",
"cls",
")",
"cls_param_dict",
"=",
"parameters_str_to_dict",
"(",
"cls_param_string",
")",
"cls_params",... | Create a documentation for a scale
Import the superclass parameters
It replaces `{superclass_parameters}` with the documentation
of the parameters from the superclass.
Parameters
----------
cls : type
A scale class
Returns
-------
cls : type
The scale class with a modified docstring. | [
"Create",
"a",
"documentation",
"for",
"a",
"scale"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L434-L488 |
233,447 | has2k1/plotnine | plotnine/doctools.py | document | def document(cls):
"""
Decorator to document a class
"""
if cls.__doc__ is None:
return cls
baseclass_name = cls.mro()[-2].__name__
try:
return DOC_FUNCTIONS[baseclass_name](cls)
except KeyError:
return cls | python | def document(cls):
if cls.__doc__ is None:
return cls
baseclass_name = cls.mro()[-2].__name__
try:
return DOC_FUNCTIONS[baseclass_name](cls)
except KeyError:
return cls | [
"def",
"document",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__doc__",
"is",
"None",
":",
"return",
"cls",
"baseclass_name",
"=",
"cls",
".",
"mro",
"(",
")",
"[",
"-",
"2",
"]",
".",
"__name__",
"try",
":",
"return",
"DOC_FUNCTIONS",
"[",
"baseclass_... | Decorator to document a class | [
"Decorator",
"to",
"document",
"a",
"class"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/doctools.py#L498-L510 |
233,448 | has2k1/plotnine | plotnine/ggplot.py | ggplot._draw_using_figure | def _draw_using_figure(self, figure, axs):
"""
Draw onto already created figure and axes
This is can be used to draw animation frames,
or inset plots. It is intended to be used
after the key plot has been drawn.
Parameters
----------
figure : ~matplotlib.figure.Figure
Matplotlib figure
axs : array_like
Array of Axes onto which to draw the plots
"""
self = deepcopy(self)
self._build()
self.theme = self.theme or theme_get()
self.figure = figure
self.axs = axs
try:
with mpl.rc_context():
self.theme.apply_rcparams()
self._setup_parameters()
self._draw_layers()
self._draw_facet_labels()
self._draw_legend()
self._apply_theme()
except Exception as err:
if self.figure is not None:
plt.close(self.figure)
raise err
return self | python | def _draw_using_figure(self, figure, axs):
self = deepcopy(self)
self._build()
self.theme = self.theme or theme_get()
self.figure = figure
self.axs = axs
try:
with mpl.rc_context():
self.theme.apply_rcparams()
self._setup_parameters()
self._draw_layers()
self._draw_facet_labels()
self._draw_legend()
self._apply_theme()
except Exception as err:
if self.figure is not None:
plt.close(self.figure)
raise err
return self | [
"def",
"_draw_using_figure",
"(",
"self",
",",
"figure",
",",
"axs",
")",
":",
"self",
"=",
"deepcopy",
"(",
"self",
")",
"self",
".",
"_build",
"(",
")",
"self",
".",
"theme",
"=",
"self",
".",
"theme",
"or",
"theme_get",
"(",
")",
"self",
".",
"f... | Draw onto already created figure and axes
This is can be used to draw animation frames,
or inset plots. It is intended to be used
after the key plot has been drawn.
Parameters
----------
figure : ~matplotlib.figure.Figure
Matplotlib figure
axs : array_like
Array of Axes onto which to draw the plots | [
"Draw",
"onto",
"already",
"created",
"figure",
"and",
"axes"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L228-L263 |
233,449 | has2k1/plotnine | plotnine/ggplot.py | ggplot._build | def _build(self):
"""
Build ggplot for rendering.
Notes
-----
This method modifies the ggplot object. The caller is
responsible for making a copy and using that to make
the method call.
"""
if not self.layers:
self += geom_blank()
self.layout = Layout()
layers = self.layers
scales = self.scales
layout = self.layout
# Give each layer a copy of the data that it will need
layers.generate_data(self.data)
# Initialise panels, add extra data for margins & missing
# facetting variables, and add on a PANEL variable to data
layout.setup(layers, self)
# Compute aesthetics to produce data with generalised
# variable names
layers.compute_aesthetics(self)
# Transform data using all scales
layers.transform(scales)
# Map and train positions so that statistics have access
# to ranges and all positions are numeric
layout.train_position(layers, scales.x, scales.y)
layout.map_position(layers)
# Apply and map statistics
layers.compute_statistic(layout)
layers.map_statistic(self)
# Make sure missing (but required) aesthetics are added
scales.add_missing(('x', 'y'))
# Prepare data in geoms
# e.g. from y and width to ymin and ymax
layers.setup_data()
# Apply position adjustments
layers.compute_position(layout)
# Reset position scales, then re-train and map. This
# ensures that facets have control over the range of
# a plot.
layout.reset_position_scales()
layout.train_position(layers, scales.x, scales.y)
layout.map_position(layers)
# Train and map non-position scales
npscales = scales.non_position_scales()
if len(npscales):
layers.train(npscales)
layers.map(npscales)
# Train coordinate system
layout.setup_panel_params(self.coordinates)
# fill in the defaults
layers.use_defaults()
# Allow stats to modify the layer data
layers.finish_statistics()
# Allow layout to modify data before rendering
layout.finish_data(layers) | python | def _build(self):
if not self.layers:
self += geom_blank()
self.layout = Layout()
layers = self.layers
scales = self.scales
layout = self.layout
# Give each layer a copy of the data that it will need
layers.generate_data(self.data)
# Initialise panels, add extra data for margins & missing
# facetting variables, and add on a PANEL variable to data
layout.setup(layers, self)
# Compute aesthetics to produce data with generalised
# variable names
layers.compute_aesthetics(self)
# Transform data using all scales
layers.transform(scales)
# Map and train positions so that statistics have access
# to ranges and all positions are numeric
layout.train_position(layers, scales.x, scales.y)
layout.map_position(layers)
# Apply and map statistics
layers.compute_statistic(layout)
layers.map_statistic(self)
# Make sure missing (but required) aesthetics are added
scales.add_missing(('x', 'y'))
# Prepare data in geoms
# e.g. from y and width to ymin and ymax
layers.setup_data()
# Apply position adjustments
layers.compute_position(layout)
# Reset position scales, then re-train and map. This
# ensures that facets have control over the range of
# a plot.
layout.reset_position_scales()
layout.train_position(layers, scales.x, scales.y)
layout.map_position(layers)
# Train and map non-position scales
npscales = scales.non_position_scales()
if len(npscales):
layers.train(npscales)
layers.map(npscales)
# Train coordinate system
layout.setup_panel_params(self.coordinates)
# fill in the defaults
layers.use_defaults()
# Allow stats to modify the layer data
layers.finish_statistics()
# Allow layout to modify data before rendering
layout.finish_data(layers) | [
"def",
"_build",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"layers",
":",
"self",
"+=",
"geom_blank",
"(",
")",
"self",
".",
"layout",
"=",
"Layout",
"(",
")",
"layers",
"=",
"self",
".",
"layers",
"scales",
"=",
"self",
".",
"scales",
"layo... | Build ggplot for rendering.
Notes
-----
This method modifies the ggplot object. The caller is
responsible for making a copy and using that to make
the method call. | [
"Build",
"ggplot",
"for",
"rendering",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L265-L339 |
233,450 | has2k1/plotnine | plotnine/ggplot.py | ggplot._setup_parameters | def _setup_parameters(self):
"""
Set facet properties
"""
# facet
self.facet.set(
layout=self.layout,
theme=self.theme,
coordinates=self.coordinates,
figure=self.figure,
axs=self.axs
)
# layout
self.layout.axs = self.axs
# theme
self.theme.figure = self.figure | python | def _setup_parameters(self):
# facet
self.facet.set(
layout=self.layout,
theme=self.theme,
coordinates=self.coordinates,
figure=self.figure,
axs=self.axs
)
# layout
self.layout.axs = self.axs
# theme
self.theme.figure = self.figure | [
"def",
"_setup_parameters",
"(",
"self",
")",
":",
"# facet",
"self",
".",
"facet",
".",
"set",
"(",
"layout",
"=",
"self",
".",
"layout",
",",
"theme",
"=",
"self",
".",
"theme",
",",
"coordinates",
"=",
"self",
".",
"coordinates",
",",
"figure",
"=",... | Set facet properties | [
"Set",
"facet",
"properties"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L341-L357 |
233,451 | has2k1/plotnine | plotnine/ggplot.py | ggplot._create_figure | def _create_figure(self):
"""
Create Matplotlib figure and axes
"""
# Good for development
if get_option('close_all_figures'):
plt.close('all')
figure = plt.figure()
axs = self.facet.make_axes(
figure,
self.layout.layout,
self.coordinates)
# Dictionary to collect matplotlib objects that will
# be targeted for theming by the themeables
figure._themeable = {}
self.figure = figure
self.axs = axs
return figure, axs | python | def _create_figure(self):
# Good for development
if get_option('close_all_figures'):
plt.close('all')
figure = plt.figure()
axs = self.facet.make_axes(
figure,
self.layout.layout,
self.coordinates)
# Dictionary to collect matplotlib objects that will
# be targeted for theming by the themeables
figure._themeable = {}
self.figure = figure
self.axs = axs
return figure, axs | [
"def",
"_create_figure",
"(",
"self",
")",
":",
"# Good for development",
"if",
"get_option",
"(",
"'close_all_figures'",
")",
":",
"plt",
".",
"close",
"(",
"'all'",
")",
"figure",
"=",
"plt",
".",
"figure",
"(",
")",
"axs",
"=",
"self",
".",
"facet",
"... | Create Matplotlib figure and axes | [
"Create",
"Matplotlib",
"figure",
"and",
"axes"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L359-L379 |
233,452 | has2k1/plotnine | plotnine/ggplot.py | ggplot._draw_facet_labels | def _draw_facet_labels(self):
"""
Draw facet labels a.k.a strip texts
"""
# Decorate the axes
# - xaxis & yaxis breaks, labels, limits, ...
# - facet labels
#
# pidx is the panel index (location left to right, top to bottom)
for pidx, layout_info in self.layout.layout.iterrows():
panel_params = self.layout.panel_params[pidx]
self.facet.set_breaks_and_labels(
panel_params, layout_info, pidx)
self.facet.draw_label(layout_info, pidx) | python | def _draw_facet_labels(self):
# Decorate the axes
# - xaxis & yaxis breaks, labels, limits, ...
# - facet labels
#
# pidx is the panel index (location left to right, top to bottom)
for pidx, layout_info in self.layout.layout.iterrows():
panel_params = self.layout.panel_params[pidx]
self.facet.set_breaks_and_labels(
panel_params, layout_info, pidx)
self.facet.draw_label(layout_info, pidx) | [
"def",
"_draw_facet_labels",
"(",
"self",
")",
":",
"# Decorate the axes",
"# - xaxis & yaxis breaks, labels, limits, ...",
"# - facet labels",
"#",
"# pidx is the panel index (location left to right, top to bottom)",
"for",
"pidx",
",",
"layout_info",
"in",
"self",
".",
"lay... | Draw facet labels a.k.a strip texts | [
"Draw",
"facet",
"labels",
"a",
".",
"k",
".",
"a",
"strip",
"texts"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L395-L408 |
233,453 | has2k1/plotnine | plotnine/ggplot.py | ggplot._draw_legend | def _draw_legend(self):
"""
Draw legend onto the figure
"""
legend_box = self.guides.build(self)
if not legend_box:
return
figure = self.figure
left = figure.subplotpars.left
right = figure.subplotpars.right
top = figure.subplotpars.top
bottom = figure.subplotpars.bottom
W, H = figure.get_size_inches()
position = self.guides.position
get_property = self.theme.themeables.property
# defaults
spacing = 0.1
strip_margin_x = 0
strip_margin_y = 0
with suppress(KeyError):
spacing = get_property('legend_box_spacing')
with suppress(KeyError):
strip_margin_x = get_property('strip_margin_x')
with suppress(KeyError):
strip_margin_y = get_property('strip_margin_y')
right_strip_width = self.facet.strip_size('right')
top_strip_height = self.facet.strip_size('top')
# Other than when the legend is on the right the rest of
# the computed x, y locations are not gauranteed not to
# overlap with the axes or the labels. The user must then
# use the legend_margin theme parameter to adjust the
# location. This should get fixed when MPL has a better
# layout manager.
if position == 'right':
loc = 6
pad = right_strip_width*(1+strip_margin_x) + spacing
x = right + pad/W
y = 0.5
elif position == 'left':
loc = 7
x = left - spacing/W
y = 0.5
elif position == 'top':
loc = 8
x = 0.5
pad = top_strip_height*(1+strip_margin_y) + spacing
y = top + pad/H
elif position == 'bottom':
loc = 9
x = 0.5
y = bottom - spacing/H
else:
loc = 10
x, y = position
anchored_box = AnchoredOffsetbox(
loc=loc,
child=legend_box,
pad=0.,
frameon=False,
bbox_to_anchor=(x, y),
bbox_transform=figure.transFigure,
borderpad=0.)
anchored_box.set_zorder(90.1)
self.figure._themeable['legend_background'] = anchored_box
ax = self.axs[0]
ax.add_artist(anchored_box) | python | def _draw_legend(self):
legend_box = self.guides.build(self)
if not legend_box:
return
figure = self.figure
left = figure.subplotpars.left
right = figure.subplotpars.right
top = figure.subplotpars.top
bottom = figure.subplotpars.bottom
W, H = figure.get_size_inches()
position = self.guides.position
get_property = self.theme.themeables.property
# defaults
spacing = 0.1
strip_margin_x = 0
strip_margin_y = 0
with suppress(KeyError):
spacing = get_property('legend_box_spacing')
with suppress(KeyError):
strip_margin_x = get_property('strip_margin_x')
with suppress(KeyError):
strip_margin_y = get_property('strip_margin_y')
right_strip_width = self.facet.strip_size('right')
top_strip_height = self.facet.strip_size('top')
# Other than when the legend is on the right the rest of
# the computed x, y locations are not gauranteed not to
# overlap with the axes or the labels. The user must then
# use the legend_margin theme parameter to adjust the
# location. This should get fixed when MPL has a better
# layout manager.
if position == 'right':
loc = 6
pad = right_strip_width*(1+strip_margin_x) + spacing
x = right + pad/W
y = 0.5
elif position == 'left':
loc = 7
x = left - spacing/W
y = 0.5
elif position == 'top':
loc = 8
x = 0.5
pad = top_strip_height*(1+strip_margin_y) + spacing
y = top + pad/H
elif position == 'bottom':
loc = 9
x = 0.5
y = bottom - spacing/H
else:
loc = 10
x, y = position
anchored_box = AnchoredOffsetbox(
loc=loc,
child=legend_box,
pad=0.,
frameon=False,
bbox_to_anchor=(x, y),
bbox_transform=figure.transFigure,
borderpad=0.)
anchored_box.set_zorder(90.1)
self.figure._themeable['legend_background'] = anchored_box
ax = self.axs[0]
ax.add_artist(anchored_box) | [
"def",
"_draw_legend",
"(",
"self",
")",
":",
"legend_box",
"=",
"self",
".",
"guides",
".",
"build",
"(",
"self",
")",
"if",
"not",
"legend_box",
":",
"return",
"figure",
"=",
"self",
".",
"figure",
"left",
"=",
"figure",
".",
"subplotpars",
".",
"lef... | Draw legend onto the figure | [
"Draw",
"legend",
"onto",
"the",
"figure"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L410-L481 |
233,454 | has2k1/plotnine | plotnine/ggplot.py | ggplot._draw_labels | def _draw_labels(self):
"""
Draw x and y labels onto the figure
"""
# This is very laboured. Should be changed when MPL
# finally has a constraint based layout manager.
figure = self.figure
get_property = self.theme.themeables.property
try:
margin = get_property('axis_title_x', 'margin')
except KeyError:
pad_x = 5
else:
pad_x = margin.get_as('t', 'pt')
try:
margin = get_property('axis_title_y', 'margin')
except KeyError:
pad_y = 5
else:
pad_y = margin.get_as('r', 'pt')
# Get the axis labels (default or specified by user)
# and let the coordinate modify them e.g. flip
labels = self.coordinates.labels({
'x': self.layout.xlabel(self.labels),
'y': self.layout.ylabel(self.labels)
})
# The first axes object is on left, and the last axes object
# is at the bottom. We change the transform so that the relevant
# coordinate is in figure coordinates. This way we take
# advantage of how MPL adjusts the label position so that they
# do not overlap with the tick text. This works well for
# facetting with scales='fixed' and also when not facetting.
# first_ax = self.axs[0]
# last_ax = self.axs[-1]
xlabel = self.facet.last_ax.set_xlabel(
labels['x'], labelpad=pad_x)
ylabel = self.facet.first_ax.set_ylabel(
labels['y'], labelpad=pad_y)
xlabel.set_transform(mtransforms.blended_transform_factory(
figure.transFigure, mtransforms.IdentityTransform()))
ylabel.set_transform(mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(), figure.transFigure))
figure._themeable['axis_title_x'] = xlabel
figure._themeable['axis_title_y'] = ylabel | python | def _draw_labels(self):
# This is very laboured. Should be changed when MPL
# finally has a constraint based layout manager.
figure = self.figure
get_property = self.theme.themeables.property
try:
margin = get_property('axis_title_x', 'margin')
except KeyError:
pad_x = 5
else:
pad_x = margin.get_as('t', 'pt')
try:
margin = get_property('axis_title_y', 'margin')
except KeyError:
pad_y = 5
else:
pad_y = margin.get_as('r', 'pt')
# Get the axis labels (default or specified by user)
# and let the coordinate modify them e.g. flip
labels = self.coordinates.labels({
'x': self.layout.xlabel(self.labels),
'y': self.layout.ylabel(self.labels)
})
# The first axes object is on left, and the last axes object
# is at the bottom. We change the transform so that the relevant
# coordinate is in figure coordinates. This way we take
# advantage of how MPL adjusts the label position so that they
# do not overlap with the tick text. This works well for
# facetting with scales='fixed' and also when not facetting.
# first_ax = self.axs[0]
# last_ax = self.axs[-1]
xlabel = self.facet.last_ax.set_xlabel(
labels['x'], labelpad=pad_x)
ylabel = self.facet.first_ax.set_ylabel(
labels['y'], labelpad=pad_y)
xlabel.set_transform(mtransforms.blended_transform_factory(
figure.transFigure, mtransforms.IdentityTransform()))
ylabel.set_transform(mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(), figure.transFigure))
figure._themeable['axis_title_x'] = xlabel
figure._themeable['axis_title_y'] = ylabel | [
"def",
"_draw_labels",
"(",
"self",
")",
":",
"# This is very laboured. Should be changed when MPL",
"# finally has a constraint based layout manager.",
"figure",
"=",
"self",
".",
"figure",
"get_property",
"=",
"self",
".",
"theme",
".",
"themeables",
".",
"property",
"t... | Draw x and y labels onto the figure | [
"Draw",
"x",
"and",
"y",
"labels",
"onto",
"the",
"figure"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L483-L533 |
233,455 | has2k1/plotnine | plotnine/ggplot.py | ggplot._draw_title | def _draw_title(self):
"""
Draw title onto the figure
"""
# This is very laboured. Should be changed when MPL
# finally has a constraint based layout manager.
figure = self.figure
title = self.labels.get('title', '')
rcParams = self.theme.rcParams
get_property = self.theme.themeables.property
# Pick suitable values in inches and convert them to
# transFigure dimension. This gives fixed spacing
# margins which work for oblong plots.
top = figure.subplotpars.top
W, H = figure.get_size_inches()
# Adjust the title to avoid overlap with the facet
# labels on the top row
# pad/H is inches in transFigure coordinates. A fixed
# margin value in inches prevents oblong plots from
# getting unpredictably large spaces.
try:
fontsize = get_property('plot_title', 'size')
except KeyError:
fontsize = float(rcParams.get('font.size', 12))
try:
linespacing = get_property('plot_title', 'linespacing')
except KeyError:
linespacing = 1.2
try:
margin = get_property('plot_title', 'margin')
except KeyError:
pad = 0.09
else:
pad = margin.get_as('b', 'in')
try:
strip_margin_x = get_property('strip_margin_x')
except KeyError:
strip_margin_x = 0
line_size = fontsize / 72.27
num_lines = len(title.split('\n'))
title_size = line_size * linespacing * num_lines
strip_height = self.facet.strip_size('top')
# vertical adjustment
strip_height *= (1 + strip_margin_x)
x = 0.5
y = top + (strip_height+title_size/2+pad)/H
text = figure.text(x, y, title, ha='center', va='center')
figure._themeable['plot_title'] = text | python | def _draw_title(self):
# This is very laboured. Should be changed when MPL
# finally has a constraint based layout manager.
figure = self.figure
title = self.labels.get('title', '')
rcParams = self.theme.rcParams
get_property = self.theme.themeables.property
# Pick suitable values in inches and convert them to
# transFigure dimension. This gives fixed spacing
# margins which work for oblong plots.
top = figure.subplotpars.top
W, H = figure.get_size_inches()
# Adjust the title to avoid overlap with the facet
# labels on the top row
# pad/H is inches in transFigure coordinates. A fixed
# margin value in inches prevents oblong plots from
# getting unpredictably large spaces.
try:
fontsize = get_property('plot_title', 'size')
except KeyError:
fontsize = float(rcParams.get('font.size', 12))
try:
linespacing = get_property('plot_title', 'linespacing')
except KeyError:
linespacing = 1.2
try:
margin = get_property('plot_title', 'margin')
except KeyError:
pad = 0.09
else:
pad = margin.get_as('b', 'in')
try:
strip_margin_x = get_property('strip_margin_x')
except KeyError:
strip_margin_x = 0
line_size = fontsize / 72.27
num_lines = len(title.split('\n'))
title_size = line_size * linespacing * num_lines
strip_height = self.facet.strip_size('top')
# vertical adjustment
strip_height *= (1 + strip_margin_x)
x = 0.5
y = top + (strip_height+title_size/2+pad)/H
text = figure.text(x, y, title, ha='center', va='center')
figure._themeable['plot_title'] = text | [
"def",
"_draw_title",
"(",
"self",
")",
":",
"# This is very laboured. Should be changed when MPL",
"# finally has a constraint based layout manager.",
"figure",
"=",
"self",
".",
"figure",
"title",
"=",
"self",
".",
"labels",
".",
"get",
"(",
"'title'",
",",
"''",
")... | Draw title onto the figure | [
"Draw",
"title",
"onto",
"the",
"figure"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L535-L590 |
233,456 | has2k1/plotnine | plotnine/ggplot.py | ggplot._apply_theme | def _apply_theme(self):
"""
Apply theme attributes to Matplotlib objects
"""
self.theme.apply_axs(self.axs)
self.theme.apply_figure(self.figure) | python | def _apply_theme(self):
self.theme.apply_axs(self.axs)
self.theme.apply_figure(self.figure) | [
"def",
"_apply_theme",
"(",
"self",
")",
":",
"self",
".",
"theme",
".",
"apply_axs",
"(",
"self",
".",
"axs",
")",
"self",
".",
"theme",
".",
"apply_figure",
"(",
"self",
".",
"figure",
")"
] | Apply theme attributes to Matplotlib objects | [
"Apply",
"theme",
"attributes",
"to",
"Matplotlib",
"objects"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L599-L604 |
233,457 | has2k1/plotnine | plotnine/ggplot.py | ggplot._save_filename | def _save_filename(self, ext):
"""
Default filename used by the save method
Parameters
----------
ext : str
Extension e.g. png, pdf, ...
"""
hash_token = abs(self.__hash__())
return 'plotnine-save-{}.{}'.format(hash_token, ext) | python | def _save_filename(self, ext):
hash_token = abs(self.__hash__())
return 'plotnine-save-{}.{}'.format(hash_token, ext) | [
"def",
"_save_filename",
"(",
"self",
",",
"ext",
")",
":",
"hash_token",
"=",
"abs",
"(",
"self",
".",
"__hash__",
"(",
")",
")",
"return",
"'plotnine-save-{}.{}'",
".",
"format",
"(",
"hash_token",
",",
"ext",
")"
] | Default filename used by the save method
Parameters
----------
ext : str
Extension e.g. png, pdf, ... | [
"Default",
"filename",
"used",
"by",
"the",
"save",
"method"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L606-L616 |
233,458 | has2k1/plotnine | plotnine/ggplot.py | ggplot.save | def save(self, filename=None, format=None, path=None,
width=None, height=None, units='in',
dpi=None, limitsize=True, verbose=True, **kwargs):
"""
Save a ggplot object as an image file
Parameters
----------
filename : str, optional
File name to write the plot to. If not specified, a name
like “plotnine-save-<hash>.<format>” is used.
format : str
Image format to use, automatically extract from
file name extension.
path : str
Path to save plot to (if you just want to set path and
not filename).
width : number, optional
Width (defaults to value set by the theme). If specified
the `height` must also be given.
height : number, optional
Height (defaults to value set by the theme). If specified
the `width` must also be given.
units : str
Units for width and height when either one is explicitly
specified (in, cm, or mm).
dpi : float
DPI to use for raster graphics. If None, defaults to using
the `dpi` of theme, if none is set then a `dpi` of 100.
limitsize : bool
If ``True`` (the default), ggsave will not save images
larger than 50x50 inches, to prevent the common error
of specifying dimensions in pixels.
verbose : bool
If ``True``, print the saving information.
kwargs : dict
Additional arguments to pass to matplotlib `savefig()`.
"""
fig_kwargs = {'bbox_inches': 'tight', # 'tight' is a good default
'format': format}
fig_kwargs.update(kwargs)
figure = [None] # nonlocal
# filename, depends on the object
if filename is None:
ext = format if format else 'pdf'
filename = self._save_filename(ext)
if path:
filename = os.path.join(path, filename)
# Preserve the users object
self = deepcopy(self)
# theme
self.theme = self.theme or theme_get()
# The figure size should be known by the theme
if width is not None and height is not None:
width = to_inches(width, units)
height = to_inches(height, units)
self += theme(figure_size=(width, height))
elif (width is None and height is not None or
width is not None and height is None):
raise PlotnineError(
"You must specify both width and height")
width, height = self.theme.themeables.property('figure_size')
if limitsize and (width > 25 or height > 25):
raise PlotnineError(
"Dimensions (width={}, height={}) exceed 25 inches "
"(height and width are specified in inches/cm/mm, "
"not pixels). If you are sure you want these "
"dimensions, use 'limitsize=False'.".format(width, height))
if dpi is None:
try:
self.theme.themeables.property('dpi')
except KeyError:
self.theme = self.theme + theme(dpi=100)
else:
self.theme = self.theme + theme(dpi=dpi)
if verbose:
warn("Saving {0} x {1} {2} image.".format(
from_inches(width, units),
from_inches(height, units), units), PlotnineWarning)
warn('Filename: {}'.format(filename), PlotnineWarning)
# Helper function so that we can clean up when it fails
def _save():
fig = figure[0] = self.draw()
# savefig ignores the figure face & edge colors
facecolor = fig.get_facecolor()
edgecolor = fig.get_edgecolor()
if edgecolor:
fig_kwargs['facecolor'] = facecolor
if edgecolor:
fig_kwargs['edgecolor'] = edgecolor
fig_kwargs['frameon'] = True
fig.savefig(filename, **fig_kwargs)
try:
_save()
except Exception as err:
figure[0] and plt.close(figure[0])
raise err
else:
figure[0] and plt.close(figure[0]) | python | def save(self, filename=None, format=None, path=None,
width=None, height=None, units='in',
dpi=None, limitsize=True, verbose=True, **kwargs):
fig_kwargs = {'bbox_inches': 'tight', # 'tight' is a good default
'format': format}
fig_kwargs.update(kwargs)
figure = [None] # nonlocal
# filename, depends on the object
if filename is None:
ext = format if format else 'pdf'
filename = self._save_filename(ext)
if path:
filename = os.path.join(path, filename)
# Preserve the users object
self = deepcopy(self)
# theme
self.theme = self.theme or theme_get()
# The figure size should be known by the theme
if width is not None and height is not None:
width = to_inches(width, units)
height = to_inches(height, units)
self += theme(figure_size=(width, height))
elif (width is None and height is not None or
width is not None and height is None):
raise PlotnineError(
"You must specify both width and height")
width, height = self.theme.themeables.property('figure_size')
if limitsize and (width > 25 or height > 25):
raise PlotnineError(
"Dimensions (width={}, height={}) exceed 25 inches "
"(height and width are specified in inches/cm/mm, "
"not pixels). If you are sure you want these "
"dimensions, use 'limitsize=False'.".format(width, height))
if dpi is None:
try:
self.theme.themeables.property('dpi')
except KeyError:
self.theme = self.theme + theme(dpi=100)
else:
self.theme = self.theme + theme(dpi=dpi)
if verbose:
warn("Saving {0} x {1} {2} image.".format(
from_inches(width, units),
from_inches(height, units), units), PlotnineWarning)
warn('Filename: {}'.format(filename), PlotnineWarning)
# Helper function so that we can clean up when it fails
def _save():
fig = figure[0] = self.draw()
# savefig ignores the figure face & edge colors
facecolor = fig.get_facecolor()
edgecolor = fig.get_edgecolor()
if edgecolor:
fig_kwargs['facecolor'] = facecolor
if edgecolor:
fig_kwargs['edgecolor'] = edgecolor
fig_kwargs['frameon'] = True
fig.savefig(filename, **fig_kwargs)
try:
_save()
except Exception as err:
figure[0] and plt.close(figure[0])
raise err
else:
figure[0] and plt.close(figure[0]) | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"format",
"=",
"None",
",",
"path",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
",",
"units",
"=",
"'in'",
",",
"dpi",
"=",
"None",
",",
"limitsize",
"=",
"Tru... | Save a ggplot object as an image file
Parameters
----------
filename : str, optional
File name to write the plot to. If not specified, a name
like “plotnine-save-<hash>.<format>” is used.
format : str
Image format to use, automatically extract from
file name extension.
path : str
Path to save plot to (if you just want to set path and
not filename).
width : number, optional
Width (defaults to value set by the theme). If specified
the `height` must also be given.
height : number, optional
Height (defaults to value set by the theme). If specified
the `width` must also be given.
units : str
Units for width and height when either one is explicitly
specified (in, cm, or mm).
dpi : float
DPI to use for raster graphics. If None, defaults to using
the `dpi` of theme, if none is set then a `dpi` of 100.
limitsize : bool
If ``True`` (the default), ggsave will not save images
larger than 50x50 inches, to prevent the common error
of specifying dimensions in pixels.
verbose : bool
If ``True``, print the saving information.
kwargs : dict
Additional arguments to pass to matplotlib `savefig()`. | [
"Save",
"a",
"ggplot",
"object",
"as",
"an",
"image",
"file"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/ggplot.py#L618-L730 |
233,459 | has2k1/plotnine | plotnine/stats/smoothers.py | mavg | def mavg(data, xseq, **params):
"""
Fit moving average
"""
window = params['method_args']['window']
# The first average comes after the full window size
# has been swept over
rolling = data['y'].rolling(**params['method_args'])
y = rolling.mean()[window:]
n = len(data)
stderr = rolling.std()[window:]
x = data['x'][window:]
data = pd.DataFrame({'x': x, 'y': y})
data.reset_index(inplace=True, drop=True)
if params['se']:
df = n - window # Original - Used
data['ymin'], data['ymax'] = tdist_ci(
y, df, stderr, params['level'])
data['se'] = stderr
return data | python | def mavg(data, xseq, **params):
window = params['method_args']['window']
# The first average comes after the full window size
# has been swept over
rolling = data['y'].rolling(**params['method_args'])
y = rolling.mean()[window:]
n = len(data)
stderr = rolling.std()[window:]
x = data['x'][window:]
data = pd.DataFrame({'x': x, 'y': y})
data.reset_index(inplace=True, drop=True)
if params['se']:
df = n - window # Original - Used
data['ymin'], data['ymax'] = tdist_ci(
y, df, stderr, params['level'])
data['se'] = stderr
return data | [
"def",
"mavg",
"(",
"data",
",",
"xseq",
",",
"*",
"*",
"params",
")",
":",
"window",
"=",
"params",
"[",
"'method_args'",
"]",
"[",
"'window'",
"]",
"# The first average comes after the full window size",
"# has been swept over",
"rolling",
"=",
"data",
"[",
"'... | Fit moving average | [
"Fit",
"moving",
"average"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/smoothers.py#L221-L243 |
233,460 | has2k1/plotnine | plotnine/stats/smoothers.py | gpr | def gpr(data, xseq, **params):
"""
Fit gaussian process
"""
try:
from sklearn import gaussian_process
except ImportError:
raise PlotnineError(
"To use gaussian process smoothing, "
"You need to install scikit-learn.")
kwargs = params['method_args']
if not kwargs:
warnings.warn(
"See sklearn.gaussian_process.GaussianProcessRegressor "
"for parameters to pass in as 'method_args'", PlotnineWarning)
regressor = gaussian_process.GaussianProcessRegressor(**kwargs)
X = np.atleast_2d(data['x']).T
n = len(data)
Xseq = np.atleast_2d(xseq).T
regressor.fit(X, data['y'])
data = pd.DataFrame({'x': xseq})
if params['se']:
y, stderr = regressor.predict(Xseq, return_std=True)
data['y'] = y
data['se'] = stderr
data['ymin'], data['ymax'] = tdist_ci(
y, n-1, stderr, params['level'])
else:
data['y'] = regressor.predict(Xseq, return_std=True)
return data | python | def gpr(data, xseq, **params):
try:
from sklearn import gaussian_process
except ImportError:
raise PlotnineError(
"To use gaussian process smoothing, "
"You need to install scikit-learn.")
kwargs = params['method_args']
if not kwargs:
warnings.warn(
"See sklearn.gaussian_process.GaussianProcessRegressor "
"for parameters to pass in as 'method_args'", PlotnineWarning)
regressor = gaussian_process.GaussianProcessRegressor(**kwargs)
X = np.atleast_2d(data['x']).T
n = len(data)
Xseq = np.atleast_2d(xseq).T
regressor.fit(X, data['y'])
data = pd.DataFrame({'x': xseq})
if params['se']:
y, stderr = regressor.predict(Xseq, return_std=True)
data['y'] = y
data['se'] = stderr
data['ymin'], data['ymax'] = tdist_ci(
y, n-1, stderr, params['level'])
else:
data['y'] = regressor.predict(Xseq, return_std=True)
return data | [
"def",
"gpr",
"(",
"data",
",",
"xseq",
",",
"*",
"*",
"params",
")",
":",
"try",
":",
"from",
"sklearn",
"import",
"gaussian_process",
"except",
"ImportError",
":",
"raise",
"PlotnineError",
"(",
"\"To use gaussian process smoothing, \"",
"\"You need to install sci... | Fit gaussian process | [
"Fit",
"gaussian",
"process"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/smoothers.py#L246-L279 |
233,461 | has2k1/plotnine | plotnine/stats/smoothers.py | tdist_ci | def tdist_ci(x, df, stderr, level):
"""
Confidence Intervals using the t-distribution
"""
q = (1 + level)/2
delta = stats.t.ppf(q, df) * stderr
return x - delta, x + delta | python | def tdist_ci(x, df, stderr, level):
q = (1 + level)/2
delta = stats.t.ppf(q, df) * stderr
return x - delta, x + delta | [
"def",
"tdist_ci",
"(",
"x",
",",
"df",
",",
"stderr",
",",
"level",
")",
":",
"q",
"=",
"(",
"1",
"+",
"level",
")",
"/",
"2",
"delta",
"=",
"stats",
".",
"t",
".",
"ppf",
"(",
"q",
",",
"df",
")",
"*",
"stderr",
"return",
"x",
"-",
"delta... | Confidence Intervals using the t-distribution | [
"Confidence",
"Intervals",
"using",
"the",
"t",
"-",
"distribution"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/smoothers.py#L282-L288 |
233,462 | has2k1/plotnine | plotnine/stats/smoothers.py | wls_prediction_std | def wls_prediction_std(res, exog=None, weights=None, alpha=0.05,
interval='confidence'):
"""
calculate standard deviation and confidence interval
Applies to WLS and OLS, not to general GLS,
that is independently but not identically distributed observations
Parameters
----------
res : regression result instance
results of WLS or OLS regression required attributes see notes
exog : array_like (optional)
exogenous variables for points to predict
weights : scalar or array_like (optional)
weights as defined for WLS (inverse of variance of observation)
alpha : float (default: alpha = 0.05)
confidence level for two-sided hypothesis
Returns
-------
predstd : array_like, 1d
standard error of prediction
same length as rows of exog
interval_l, interval_u : array_like
lower und upper confidence bounds
Notes
-----
The result instance needs to have at least the following
res.model.predict() : predicted values or
res.fittedvalues : values used in estimation
res.cov_params() : covariance matrix of parameter estimates
If exog is 1d, then it is interpreted as one observation,
i.e. a row vector.
testing status: not compared with other packages
References
----------
Greene p.111 for OLS, extended to WLS by analogy
"""
# work around current bug:
# fit doesn't attach results to model, predict broken
# res.model.results
covb = res.cov_params()
if exog is None:
exog = res.model.exog
predicted = res.fittedvalues
if weights is None:
weights = res.model.weights
else:
exog = np.atleast_2d(exog)
if covb.shape[1] != exog.shape[1]:
raise ValueError('wrong shape of exog')
predicted = res.model.predict(res.params, exog)
if weights is None:
weights = 1.
else:
weights = np.asarray(weights)
if weights.size > 1 and len(weights) != exog.shape[0]:
raise ValueError('weights and exog do not have matching shape')
# full covariance:
# predvar = res3.mse_resid + np.diag(np.dot(X2,np.dot(covb,X2.T)))
# predication variance only
predvar = res.mse_resid/weights
ip = (exog * np.dot(covb, exog.T).T).sum(1)
if interval == 'confidence':
predstd = np.sqrt(ip)
elif interval == 'prediction':
predstd = np.sqrt(ip + predvar)
tppf = stats.t.isf(alpha/2., res.df_resid)
interval_u = predicted + tppf * predstd
interval_l = predicted - tppf * predstd
return predstd, interval_l, interval_u | python | def wls_prediction_std(res, exog=None, weights=None, alpha=0.05,
interval='confidence'):
# work around current bug:
# fit doesn't attach results to model, predict broken
# res.model.results
covb = res.cov_params()
if exog is None:
exog = res.model.exog
predicted = res.fittedvalues
if weights is None:
weights = res.model.weights
else:
exog = np.atleast_2d(exog)
if covb.shape[1] != exog.shape[1]:
raise ValueError('wrong shape of exog')
predicted = res.model.predict(res.params, exog)
if weights is None:
weights = 1.
else:
weights = np.asarray(weights)
if weights.size > 1 and len(weights) != exog.shape[0]:
raise ValueError('weights and exog do not have matching shape')
# full covariance:
# predvar = res3.mse_resid + np.diag(np.dot(X2,np.dot(covb,X2.T)))
# predication variance only
predvar = res.mse_resid/weights
ip = (exog * np.dot(covb, exog.T).T).sum(1)
if interval == 'confidence':
predstd = np.sqrt(ip)
elif interval == 'prediction':
predstd = np.sqrt(ip + predvar)
tppf = stats.t.isf(alpha/2., res.df_resid)
interval_u = predicted + tppf * predstd
interval_l = predicted - tppf * predstd
return predstd, interval_l, interval_u | [
"def",
"wls_prediction_std",
"(",
"res",
",",
"exog",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"alpha",
"=",
"0.05",
",",
"interval",
"=",
"'confidence'",
")",
":",
"# work around current bug:",
"# fit doesn't attach results to model, predict broken",
"# res.... | calculate standard deviation and confidence interval
Applies to WLS and OLS, not to general GLS,
that is independently but not identically distributed observations
Parameters
----------
res : regression result instance
results of WLS or OLS regression required attributes see notes
exog : array_like (optional)
exogenous variables for points to predict
weights : scalar or array_like (optional)
weights as defined for WLS (inverse of variance of observation)
alpha : float (default: alpha = 0.05)
confidence level for two-sided hypothesis
Returns
-------
predstd : array_like, 1d
standard error of prediction
same length as rows of exog
interval_l, interval_u : array_like
lower und upper confidence bounds
Notes
-----
The result instance needs to have at least the following
res.model.predict() : predicted values or
res.fittedvalues : values used in estimation
res.cov_params() : covariance matrix of parameter estimates
If exog is 1d, then it is interpreted as one observation,
i.e. a row vector.
testing status: not compared with other packages
References
----------
Greene p.111 for OLS, extended to WLS by analogy | [
"calculate",
"standard",
"deviation",
"and",
"confidence",
"interval"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/stats/smoothers.py#L293-L371 |
233,463 | has2k1/plotnine | plotnine/facets/layout.py | Layout.setup | def setup(self, layers, plot):
"""
Create a layout for the panels
The layout is a dataframe that stores all the
structual information about the panels that will
make up the plot. The actual layout depends on
the type of facet.
This method ensures that each layer has a copy of the
data it needs in `layer.data`. That data is also has
column `PANEL` that indicates the panel onto which each
data row/item will be plotted.
"""
data = [l.data for l in layers]
# setup facets
self.facet = plot.facet
self.facet.setup_params(data)
data = self.facet.setup_data(data)
# setup coords
self.coord = plot.coordinates
self.coord.setup_params(data)
data = self.coord.setup_data(data)
# Generate panel layout
data = self.facet.setup_data(data)
self.layout = self.facet.compute_layout(data)
self.layout = self.coord.setup_layout(self.layout)
self.check_layout()
# Map the data to the panels
for layer, ldata in zip(layers, data):
layer.data = self.facet.map(ldata, self.layout) | python | def setup(self, layers, plot):
data = [l.data for l in layers]
# setup facets
self.facet = plot.facet
self.facet.setup_params(data)
data = self.facet.setup_data(data)
# setup coords
self.coord = plot.coordinates
self.coord.setup_params(data)
data = self.coord.setup_data(data)
# Generate panel layout
data = self.facet.setup_data(data)
self.layout = self.facet.compute_layout(data)
self.layout = self.coord.setup_layout(self.layout)
self.check_layout()
# Map the data to the panels
for layer, ldata in zip(layers, data):
layer.data = self.facet.map(ldata, self.layout) | [
"def",
"setup",
"(",
"self",
",",
"layers",
",",
"plot",
")",
":",
"data",
"=",
"[",
"l",
".",
"data",
"for",
"l",
"in",
"layers",
"]",
"# setup facets",
"self",
".",
"facet",
"=",
"plot",
".",
"facet",
"self",
".",
"facet",
".",
"setup_params",
"(... | Create a layout for the panels
The layout is a dataframe that stores all the
structual information about the panels that will
make up the plot. The actual layout depends on
the type of facet.
This method ensures that each layer has a copy of the
data it needs in `layer.data`. That data is also has
column `PANEL` that indicates the panel onto which each
data row/item will be plotted. | [
"Create",
"a",
"layout",
"for",
"the",
"panels"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L30-L64 |
233,464 | has2k1/plotnine | plotnine/facets/layout.py | Layout.train_position | def train_position(self, layers, x_scale, y_scale):
"""
Create all the required x & y panel_scales y_scales
and set the ranges for each scale according to the data.
Notes
-----
The number of x or y scales depends on the facetting,
particularly the scales parameter. e.g if `scales='free'`
then each panel will have separate x and y scales, and
if `scales='fixed'` then all panels will share an x
scale and a y scale.
"""
layout = self.layout
if self.panel_scales_x is None and x_scale:
result = self.facet.init_scales(layout, x_scale, None)
self.panel_scales_x = result.x
if self.panel_scales_y is None and y_scale:
result = self.facet.init_scales(layout, None, y_scale)
self.panel_scales_y = result.y
self.facet.train_position_scales(self, layers) | python | def train_position(self, layers, x_scale, y_scale):
layout = self.layout
if self.panel_scales_x is None and x_scale:
result = self.facet.init_scales(layout, x_scale, None)
self.panel_scales_x = result.x
if self.panel_scales_y is None and y_scale:
result = self.facet.init_scales(layout, None, y_scale)
self.panel_scales_y = result.y
self.facet.train_position_scales(self, layers) | [
"def",
"train_position",
"(",
"self",
",",
"layers",
",",
"x_scale",
",",
"y_scale",
")",
":",
"layout",
"=",
"self",
".",
"layout",
"if",
"self",
".",
"panel_scales_x",
"is",
"None",
"and",
"x_scale",
":",
"result",
"=",
"self",
".",
"facet",
".",
"in... | Create all the required x & y panel_scales y_scales
and set the ranges for each scale according to the data.
Notes
-----
The number of x or y scales depends on the facetting,
particularly the scales parameter. e.g if `scales='free'`
then each panel will have separate x and y scales, and
if `scales='fixed'` then all panels will share an x
scale and a y scale. | [
"Create",
"all",
"the",
"required",
"x",
"&",
"y",
"panel_scales",
"y_scales",
"and",
"set",
"the",
"ranges",
"for",
"each",
"scale",
"according",
"to",
"the",
"data",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L66-L88 |
233,465 | has2k1/plotnine | plotnine/facets/layout.py | Layout.get_scales | def get_scales(self, i):
"""
Return x & y scales for panel i
Parameters
----------
i : int
Panel id
Returns
-------
scales : types.SimpleNamespace
Class attributes *x* for the x scale and *y*
for the y scale of the panel
"""
# wrapping with np.asarray prevents an exception
# on some datasets
bool_idx = (np.asarray(self.layout['PANEL']) == i)
xsc = None
ysc = None
if self.panel_scales_x:
idx = self.layout.loc[bool_idx, 'SCALE_X'].values[0]
xsc = self.panel_scales_x[idx-1]
if self.panel_scales_y:
idx = self.layout.loc[bool_idx, 'SCALE_Y'].values[0]
ysc = self.panel_scales_y[idx-1]
return types.SimpleNamespace(x=xsc, y=ysc) | python | def get_scales(self, i):
# wrapping with np.asarray prevents an exception
# on some datasets
bool_idx = (np.asarray(self.layout['PANEL']) == i)
xsc = None
ysc = None
if self.panel_scales_x:
idx = self.layout.loc[bool_idx, 'SCALE_X'].values[0]
xsc = self.panel_scales_x[idx-1]
if self.panel_scales_y:
idx = self.layout.loc[bool_idx, 'SCALE_Y'].values[0]
ysc = self.panel_scales_y[idx-1]
return types.SimpleNamespace(x=xsc, y=ysc) | [
"def",
"get_scales",
"(",
"self",
",",
"i",
")",
":",
"# wrapping with np.asarray prevents an exception",
"# on some datasets",
"bool_idx",
"=",
"(",
"np",
".",
"asarray",
"(",
"self",
".",
"layout",
"[",
"'PANEL'",
"]",
")",
"==",
"i",
")",
"xsc",
"=",
"Non... | Return x & y scales for panel i
Parameters
----------
i : int
Panel id
Returns
-------
scales : types.SimpleNamespace
Class attributes *x* for the x scale and *y*
for the y scale of the panel | [
"Return",
"x",
"&",
"y",
"scales",
"for",
"panel",
"i"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L116-L146 |
233,466 | has2k1/plotnine | plotnine/facets/layout.py | Layout.reset_position_scales | def reset_position_scales(self):
"""
Reset x and y scales
"""
if not self.facet.shrink:
return
with suppress(AttributeError):
self.panel_scales_x.reset()
with suppress(AttributeError):
self.panel_scales_y.reset() | python | def reset_position_scales(self):
if not self.facet.shrink:
return
with suppress(AttributeError):
self.panel_scales_x.reset()
with suppress(AttributeError):
self.panel_scales_y.reset() | [
"def",
"reset_position_scales",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"facet",
".",
"shrink",
":",
"return",
"with",
"suppress",
"(",
"AttributeError",
")",
":",
"self",
".",
"panel_scales_x",
".",
"reset",
"(",
")",
"with",
"suppress",
"(",
"... | Reset x and y scales | [
"Reset",
"x",
"and",
"y",
"scales"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L148-L159 |
233,467 | has2k1/plotnine | plotnine/facets/layout.py | Layout.setup_panel_params | def setup_panel_params(self, coord):
"""
Calculate the x & y range & breaks information for each panel
Parameters
----------
coord : coord
Coordinate
"""
if not self.panel_scales_x:
raise PlotnineError('Missing an x scale')
if not self.panel_scales_y:
raise PlotnineError('Missing a y scale')
self.panel_params = []
cols = ['SCALE_X', 'SCALE_Y']
for i, j in self.layout[cols].itertuples(index=False):
i, j = i-1, j-1
params = coord.setup_panel_params(
self.panel_scales_x[i],
self.panel_scales_y[j])
self.panel_params.append(params) | python | def setup_panel_params(self, coord):
if not self.panel_scales_x:
raise PlotnineError('Missing an x scale')
if not self.panel_scales_y:
raise PlotnineError('Missing a y scale')
self.panel_params = []
cols = ['SCALE_X', 'SCALE_Y']
for i, j in self.layout[cols].itertuples(index=False):
i, j = i-1, j-1
params = coord.setup_panel_params(
self.panel_scales_x[i],
self.panel_scales_y[j])
self.panel_params.append(params) | [
"def",
"setup_panel_params",
"(",
"self",
",",
"coord",
")",
":",
"if",
"not",
"self",
".",
"panel_scales_x",
":",
"raise",
"PlotnineError",
"(",
"'Missing an x scale'",
")",
"if",
"not",
"self",
".",
"panel_scales_y",
":",
"raise",
"PlotnineError",
"(",
"'Mis... | Calculate the x & y range & breaks information for each panel
Parameters
----------
coord : coord
Coordinate | [
"Calculate",
"the",
"x",
"&",
"y",
"range",
"&",
"breaks",
"information",
"for",
"each",
"panel"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L161-L183 |
233,468 | has2k1/plotnine | plotnine/facets/layout.py | Layout.finish_data | def finish_data(self, layers):
"""
Modify data before it is drawn out by the geom
Parameters
----------
layers : list
List of layers
"""
for layer in layers:
layer.data = self.facet.finish_data(layer.data, self) | python | def finish_data(self, layers):
for layer in layers:
layer.data = self.facet.finish_data(layer.data, self) | [
"def",
"finish_data",
"(",
"self",
",",
"layers",
")",
":",
"for",
"layer",
"in",
"layers",
":",
"layer",
".",
"data",
"=",
"self",
".",
"facet",
".",
"finish_data",
"(",
"layer",
".",
"data",
",",
"self",
")"
] | Modify data before it is drawn out by the geom
Parameters
----------
layers : list
List of layers | [
"Modify",
"data",
"before",
"it",
"is",
"drawn",
"out",
"by",
"the",
"geom"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/layout.py#L185-L195 |
233,469 | has2k1/plotnine | plotnine/guides/guide.py | guide._set_defaults | def _set_defaults(self):
"""
Set configuration parameters for drawing guide
"""
valid_locations = {'top', 'bottom', 'left', 'right'}
horizontal_locations = {'left', 'right'}
get_property = self.theme.themeables.property
margin_location_lookup = {'t': 'b', 'b': 't',
'l': 'r', 'r': 'l'}
# label position
self.label_position = self.label_position or 'right'
if self.label_position not in valid_locations:
msg = "label position '{}' is invalid"
raise PlotnineError(msg.format(self.label_position))
# label margin
# legend_text_legend or legend_text_colorbar
name = 'legend_text_{}'.format(
self.__class__.__name__.split('_')[-1])
loc = margin_location_lookup[self.label_position[0]]
try:
margin = get_property(name, 'margin')
except KeyError:
self._label_margin = 3
else:
self._label_margin = margin.get_as(loc, 'pt')
# direction of guide
if self.direction is None:
if self.label_position in horizontal_locations:
self.direction = 'vertical'
else:
self.direction = 'horizontal'
# title position
if self.title_position is None:
if self.direction == 'vertical':
self.title_position = 'top'
elif self.direction == 'horizontal':
self.title_position = 'left'
if self.title_position not in valid_locations:
msg = "title position '{}' is invalid"
raise PlotnineError(msg.format(self.title_position))
# title alignment
tmp = 'left' if self.direction == 'vertical' else 'center'
self._title_align = self._default('legend_title_align', tmp)
# by default, direction of each guide depends on
# the position all the guides
try:
position = get_property('legend_position')
except KeyError:
position = 'right'
if position in {'top', 'bottom'}:
tmp = 'horizontal'
else: # left, right, (default)
tmp = 'vertical'
self.direction = self._default('legend_direction', tmp)
# title margin
loc = margin_location_lookup[self.title_position[0]]
try:
margin = get_property('legend_title', 'margin')
except KeyError:
self._title_margin = 8
else:
self._title_margin = margin.get_as(loc, 'pt')
# legend_margin
try:
self._legend_margin = get_property('legend_margin')
except KeyError:
self._legend_margin = 10
# legend_entry_spacing
try:
self._legend_entry_spacing_x = get_property(
'legend_entry_spacing_x')
except KeyError:
self._legend_entry_spacing_x = 5
try:
self._legend_entry_spacing_y = get_property(
'legend_entry_spacing_y')
except KeyError:
self._legend_entry_spacing_y = 2 | python | def _set_defaults(self):
valid_locations = {'top', 'bottom', 'left', 'right'}
horizontal_locations = {'left', 'right'}
get_property = self.theme.themeables.property
margin_location_lookup = {'t': 'b', 'b': 't',
'l': 'r', 'r': 'l'}
# label position
self.label_position = self.label_position or 'right'
if self.label_position not in valid_locations:
msg = "label position '{}' is invalid"
raise PlotnineError(msg.format(self.label_position))
# label margin
# legend_text_legend or legend_text_colorbar
name = 'legend_text_{}'.format(
self.__class__.__name__.split('_')[-1])
loc = margin_location_lookup[self.label_position[0]]
try:
margin = get_property(name, 'margin')
except KeyError:
self._label_margin = 3
else:
self._label_margin = margin.get_as(loc, 'pt')
# direction of guide
if self.direction is None:
if self.label_position in horizontal_locations:
self.direction = 'vertical'
else:
self.direction = 'horizontal'
# title position
if self.title_position is None:
if self.direction == 'vertical':
self.title_position = 'top'
elif self.direction == 'horizontal':
self.title_position = 'left'
if self.title_position not in valid_locations:
msg = "title position '{}' is invalid"
raise PlotnineError(msg.format(self.title_position))
# title alignment
tmp = 'left' if self.direction == 'vertical' else 'center'
self._title_align = self._default('legend_title_align', tmp)
# by default, direction of each guide depends on
# the position all the guides
try:
position = get_property('legend_position')
except KeyError:
position = 'right'
if position in {'top', 'bottom'}:
tmp = 'horizontal'
else: # left, right, (default)
tmp = 'vertical'
self.direction = self._default('legend_direction', tmp)
# title margin
loc = margin_location_lookup[self.title_position[0]]
try:
margin = get_property('legend_title', 'margin')
except KeyError:
self._title_margin = 8
else:
self._title_margin = margin.get_as(loc, 'pt')
# legend_margin
try:
self._legend_margin = get_property('legend_margin')
except KeyError:
self._legend_margin = 10
# legend_entry_spacing
try:
self._legend_entry_spacing_x = get_property(
'legend_entry_spacing_x')
except KeyError:
self._legend_entry_spacing_x = 5
try:
self._legend_entry_spacing_y = get_property(
'legend_entry_spacing_y')
except KeyError:
self._legend_entry_spacing_y = 2 | [
"def",
"_set_defaults",
"(",
"self",
")",
":",
"valid_locations",
"=",
"{",
"'top'",
",",
"'bottom'",
",",
"'left'",
",",
"'right'",
"}",
"horizontal_locations",
"=",
"{",
"'left'",
",",
"'right'",
"}",
"get_property",
"=",
"self",
".",
"theme",
".",
"them... | Set configuration parameters for drawing guide | [
"Set",
"configuration",
"parameters",
"for",
"drawing",
"guide"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide.py#L107-L195 |
233,470 | has2k1/plotnine | plotnine/guides/guide.py | guide.legend_aesthetics | def legend_aesthetics(self, layer, plot):
"""
Return the aesthetics that contribute to the legend
Parameters
----------
layer : Layer
Layer whose legend is to be drawn
plot : ggplot
Plot object
Returns
-------
matched : list
List of the names of the aethetics that contribute
to the legend.
"""
l = layer
legend_ae = set(self.key.columns) - {'label'}
all_ae = (l.mapping.keys() |
(plot.mapping if l.inherit_aes else set()) |
l.stat.DEFAULT_AES.keys())
geom_ae = l.geom.REQUIRED_AES | l.geom.DEFAULT_AES.keys()
matched = all_ae & geom_ae & legend_ae
matched = list(matched - set(l.geom.aes_params))
return matched | python | def legend_aesthetics(self, layer, plot):
l = layer
legend_ae = set(self.key.columns) - {'label'}
all_ae = (l.mapping.keys() |
(plot.mapping if l.inherit_aes else set()) |
l.stat.DEFAULT_AES.keys())
geom_ae = l.geom.REQUIRED_AES | l.geom.DEFAULT_AES.keys()
matched = all_ae & geom_ae & legend_ae
matched = list(matched - set(l.geom.aes_params))
return matched | [
"def",
"legend_aesthetics",
"(",
"self",
",",
"layer",
",",
"plot",
")",
":",
"l",
"=",
"layer",
"legend_ae",
"=",
"set",
"(",
"self",
".",
"key",
".",
"columns",
")",
"-",
"{",
"'label'",
"}",
"all_ae",
"=",
"(",
"l",
".",
"mapping",
".",
"keys",
... | Return the aesthetics that contribute to the legend
Parameters
----------
layer : Layer
Layer whose legend is to be drawn
plot : ggplot
Plot object
Returns
-------
matched : list
List of the names of the aethetics that contribute
to the legend. | [
"Return",
"the",
"aesthetics",
"that",
"contribute",
"to",
"the",
"legend"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide.py#L197-L222 |
233,471 | has2k1/plotnine | plotnine/scales/scale.py | scale.train_df | def train_df(self, df):
"""
Train scale from a dataframe
"""
aesthetics = sorted(set(self.aesthetics) & set(df.columns))
for ae in aesthetics:
self.train(df[ae]) | python | def train_df(self, df):
aesthetics = sorted(set(self.aesthetics) & set(df.columns))
for ae in aesthetics:
self.train(df[ae]) | [
"def",
"train_df",
"(",
"self",
",",
"df",
")",
":",
"aesthetics",
"=",
"sorted",
"(",
"set",
"(",
"self",
".",
"aesthetics",
")",
"&",
"set",
"(",
"df",
".",
"columns",
")",
")",
"for",
"ae",
"in",
"aesthetics",
":",
"self",
".",
"train",
"(",
"... | Train scale from a dataframe | [
"Train",
"scale",
"from",
"a",
"dataframe"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/scale.py#L214-L220 |
233,472 | has2k1/plotnine | plotnine/guides/guide_legend.py | guide_legend.train | def train(self, scale, aesthetic=None):
"""
Create the key for the guide
The key is a dataframe with two columns:
- scale name : values
- label : labels for each value
scale name is one of the aesthetics
['x', 'y', 'color', 'fill', 'size', 'shape', 'alpha',
'stroke']
Returns this guide if training is successful and None
if it fails
"""
if aesthetic is None:
aesthetic = scale.aesthetics[0]
breaks = scale.get_breaks()
if isinstance(breaks, OrderedDict):
if all([np.isnan(x) for x in breaks.values()]):
return None
elif not len(breaks) or all(np.isnan(breaks)):
return None
with suppress(AttributeError):
breaks = list(breaks.keys())
key = pd.DataFrame({
aesthetic: scale.map(breaks),
'label': scale.get_labels(breaks)})
# Drop out-of-range values for continuous scale
# (should use scale$oob?)
# Currently, numpy does not deal with NA (Not available)
# When they are introduced, the block below should be
# adjusted likewise, see ggplot2, guide-lengend.r
if isinstance(scale, scale_continuous):
limits = scale.limits
b = np.asarray(breaks)
noob = np.logical_and(limits[0] <= b,
b <= limits[1])
key = key[noob]
if len(key) == 0:
return None
self.key = key
# create a hash of the important information in the guide
labels = ' '.join(str(x) for x in self.key['label'])
info = '\n'.join([self.title, labels, str(self.direction),
self.__class__.__name__])
self.hash = hashlib.md5(info.encode('utf-8')).hexdigest()
return self | python | def train(self, scale, aesthetic=None):
if aesthetic is None:
aesthetic = scale.aesthetics[0]
breaks = scale.get_breaks()
if isinstance(breaks, OrderedDict):
if all([np.isnan(x) for x in breaks.values()]):
return None
elif not len(breaks) or all(np.isnan(breaks)):
return None
with suppress(AttributeError):
breaks = list(breaks.keys())
key = pd.DataFrame({
aesthetic: scale.map(breaks),
'label': scale.get_labels(breaks)})
# Drop out-of-range values for continuous scale
# (should use scale$oob?)
# Currently, numpy does not deal with NA (Not available)
# When they are introduced, the block below should be
# adjusted likewise, see ggplot2, guide-lengend.r
if isinstance(scale, scale_continuous):
limits = scale.limits
b = np.asarray(breaks)
noob = np.logical_and(limits[0] <= b,
b <= limits[1])
key = key[noob]
if len(key) == 0:
return None
self.key = key
# create a hash of the important information in the guide
labels = ' '.join(str(x) for x in self.key['label'])
info = '\n'.join([self.title, labels, str(self.direction),
self.__class__.__name__])
self.hash = hashlib.md5(info.encode('utf-8')).hexdigest()
return self | [
"def",
"train",
"(",
"self",
",",
"scale",
",",
"aesthetic",
"=",
"None",
")",
":",
"if",
"aesthetic",
"is",
"None",
":",
"aesthetic",
"=",
"scale",
".",
"aesthetics",
"[",
"0",
"]",
"breaks",
"=",
"scale",
".",
"get_breaks",
"(",
")",
"if",
"isinsta... | Create the key for the guide
The key is a dataframe with two columns:
- scale name : values
- label : labels for each value
scale name is one of the aesthetics
['x', 'y', 'color', 'fill', 'size', 'shape', 'alpha',
'stroke']
Returns this guide if training is successful and None
if it fails | [
"Create",
"the",
"key",
"for",
"the",
"guide"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide_legend.py#L54-L108 |
233,473 | has2k1/plotnine | plotnine/guides/guide_legend.py | guide_legend.create_geoms | def create_geoms(self, plot):
"""
Make information needed to draw a legend for each of the layers.
For each layer, that information is a dictionary with the geom
to draw the guide together with the data and the parameters that
will be used in the call to geom.
"""
def get_legend_geom(layer):
if hasattr(layer.geom, 'draw_legend'):
geom = layer.geom.__class__
else:
name = 'geom_{}'.format(layer.geom.legend_geom)
geom = Registry[name]
return geom
# A layer either contributes to the guide, or it does not. The
# guide entries may be ploted in the layers
self.glayers = []
for l in plot.layers:
exclude = set()
if isinstance(l.show_legend, dict):
l.show_legend = rename_aesthetics(l.show_legend)
exclude = {ae for ae, val in l.show_legend.items()
if not val}
elif l.show_legend not in (None, True):
continue
matched = self.legend_aesthetics(l, plot)
# This layer does not contribute to the legend
if not set(matched) - exclude:
continue
data = self.key[matched].copy()
data = l.use_defaults(data)
# override.aes in guide_legend manually changes the geom
for ae in set(self.override_aes) & set(data.columns):
data[ae] = self.override_aes[ae]
geom = get_legend_geom(l)
data = remove_missing(
data, l.geom.params['na_rm'],
list(l.geom.REQUIRED_AES | l.geom.NON_MISSING_AES),
'{} legend'.format(l.geom.__class__.__name__))
self.glayers.append(
types.SimpleNamespace(geom=geom, data=data, layer=l))
if not self.glayers:
return None
return self | python | def create_geoms(self, plot):
def get_legend_geom(layer):
if hasattr(layer.geom, 'draw_legend'):
geom = layer.geom.__class__
else:
name = 'geom_{}'.format(layer.geom.legend_geom)
geom = Registry[name]
return geom
# A layer either contributes to the guide, or it does not. The
# guide entries may be ploted in the layers
self.glayers = []
for l in plot.layers:
exclude = set()
if isinstance(l.show_legend, dict):
l.show_legend = rename_aesthetics(l.show_legend)
exclude = {ae for ae, val in l.show_legend.items()
if not val}
elif l.show_legend not in (None, True):
continue
matched = self.legend_aesthetics(l, plot)
# This layer does not contribute to the legend
if not set(matched) - exclude:
continue
data = self.key[matched].copy()
data = l.use_defaults(data)
# override.aes in guide_legend manually changes the geom
for ae in set(self.override_aes) & set(data.columns):
data[ae] = self.override_aes[ae]
geom = get_legend_geom(l)
data = remove_missing(
data, l.geom.params['na_rm'],
list(l.geom.REQUIRED_AES | l.geom.NON_MISSING_AES),
'{} legend'.format(l.geom.__class__.__name__))
self.glayers.append(
types.SimpleNamespace(geom=geom, data=data, layer=l))
if not self.glayers:
return None
return self | [
"def",
"create_geoms",
"(",
"self",
",",
"plot",
")",
":",
"def",
"get_legend_geom",
"(",
"layer",
")",
":",
"if",
"hasattr",
"(",
"layer",
".",
"geom",
",",
"'draw_legend'",
")",
":",
"geom",
"=",
"layer",
".",
"geom",
".",
"__class__",
"else",
":",
... | Make information needed to draw a legend for each of the layers.
For each layer, that information is a dictionary with the geom
to draw the guide together with the data and the parameters that
will be used in the call to geom. | [
"Make",
"information",
"needed",
"to",
"draw",
"a",
"legend",
"for",
"each",
"of",
"the",
"layers",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/guides/guide_legend.py#L132-L182 |
233,474 | has2k1/plotnine | setup.py | get_package_data | def get_package_data():
"""
Return package data
For example:
{'': ['*.txt', '*.rst'],
'hello': ['*.msg']}
means:
- If any package contains *.txt or *.rst files,
include them
- And include any *.msg files found in
the 'hello' package, too:
"""
baseline_images = [
'tests/baseline_images/%s/*' % x
for x in os.listdir('plotnine/tests/baseline_images')]
csv_data = ['data/*.csv']
package_data = {'plotnine': baseline_images + csv_data}
return package_data | python | def get_package_data():
baseline_images = [
'tests/baseline_images/%s/*' % x
for x in os.listdir('plotnine/tests/baseline_images')]
csv_data = ['data/*.csv']
package_data = {'plotnine': baseline_images + csv_data}
return package_data | [
"def",
"get_package_data",
"(",
")",
":",
"baseline_images",
"=",
"[",
"'tests/baseline_images/%s/*'",
"%",
"x",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"'plotnine/tests/baseline_images'",
")",
"]",
"csv_data",
"=",
"[",
"'data/*.csv'",
"]",
"package_data",
... | Return package data
For example:
{'': ['*.txt', '*.rst'],
'hello': ['*.msg']}
means:
- If any package contains *.txt or *.rst files,
include them
- And include any *.msg files found in
the 'hello' package, too: | [
"Return",
"package",
"data"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/setup.py#L73-L93 |
233,475 | has2k1/plotnine | plotnine/__init__.py | _get_all_imports | def _get_all_imports():
"""
Return list of all the imports
This prevents sub-modules (geoms, stats, utils, ...)
from being imported into the user namespace by the
following import statement
from plotnine import *
This is because `from Module import Something`
leads to `Module` itself coming into the namespace!!
"""
import types
lst = [name for name, obj in globals().items()
if not (name.startswith('_') or
name == 'absolute_import' or
isinstance(obj, types.ModuleType))]
return lst | python | def _get_all_imports():
import types
lst = [name for name, obj in globals().items()
if not (name.startswith('_') or
name == 'absolute_import' or
isinstance(obj, types.ModuleType))]
return lst | [
"def",
"_get_all_imports",
"(",
")",
":",
"import",
"types",
"lst",
"=",
"[",
"name",
"for",
"name",
",",
"obj",
"in",
"globals",
"(",
")",
".",
"items",
"(",
")",
"if",
"not",
"(",
"name",
".",
"startswith",
"(",
"'_'",
")",
"or",
"name",
"==",
... | Return list of all the imports
This prevents sub-modules (geoms, stats, utils, ...)
from being imported into the user namespace by the
following import statement
from plotnine import *
This is because `from Module import Something`
leads to `Module` itself coming into the namespace!! | [
"Return",
"list",
"of",
"all",
"the",
"imports"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/__init__.py#L22-L40 |
233,476 | has2k1/plotnine | plotnine/geoms/geom_rect.py | _rectangles_to_polygons | def _rectangles_to_polygons(df):
"""
Convert rect data to polygons
Paramters
---------
df : dataframe
Dataframe with *xmin*, *xmax*, *ymin* and *ymax* columns,
plus others for aesthetics ...
Returns
-------
data : dataframe
Dataframe with *x* and *y* columns, plus others for
aesthetics ...
"""
n = len(df)
# Helper indexing arrays
xmin_idx = np.tile([True, True, False, False], n)
xmax_idx = ~xmin_idx
ymin_idx = np.tile([True, False, False, True], n)
ymax_idx = ~ymin_idx
# There are 2 x and 2 y values for each of xmin, xmax, ymin & ymax
# The positions are as layed out in the indexing arrays
# x and y values
x = np.empty(n*4)
y = np.empty(n*4)
x[xmin_idx] = df['xmin'].repeat(2)
x[xmax_idx] = df['xmax'].repeat(2)
y[ymin_idx] = df['ymin'].repeat(2)
y[ymax_idx] = df['ymax'].repeat(2)
# Aesthetic columns and others
other_cols = df.columns.difference(
['x', 'y', 'xmin', 'xmax', 'ymin', 'ymax'])
d = {col: np.repeat(df[col].values, 4) for col in other_cols}
data = pd.DataFrame({
'x': x,
'y': y,
**d
})
return data | python | def _rectangles_to_polygons(df):
n = len(df)
# Helper indexing arrays
xmin_idx = np.tile([True, True, False, False], n)
xmax_idx = ~xmin_idx
ymin_idx = np.tile([True, False, False, True], n)
ymax_idx = ~ymin_idx
# There are 2 x and 2 y values for each of xmin, xmax, ymin & ymax
# The positions are as layed out in the indexing arrays
# x and y values
x = np.empty(n*4)
y = np.empty(n*4)
x[xmin_idx] = df['xmin'].repeat(2)
x[xmax_idx] = df['xmax'].repeat(2)
y[ymin_idx] = df['ymin'].repeat(2)
y[ymax_idx] = df['ymax'].repeat(2)
# Aesthetic columns and others
other_cols = df.columns.difference(
['x', 'y', 'xmin', 'xmax', 'ymin', 'ymax'])
d = {col: np.repeat(df[col].values, 4) for col in other_cols}
data = pd.DataFrame({
'x': x,
'y': y,
**d
})
return data | [
"def",
"_rectangles_to_polygons",
"(",
"df",
")",
":",
"n",
"=",
"len",
"(",
"df",
")",
"# Helper indexing arrays",
"xmin_idx",
"=",
"np",
".",
"tile",
"(",
"[",
"True",
",",
"True",
",",
"False",
",",
"False",
"]",
",",
"n",
")",
"xmax_idx",
"=",
"~... | Convert rect data to polygons
Paramters
---------
df : dataframe
Dataframe with *xmin*, *xmax*, *ymin* and *ymax* columns,
plus others for aesthetics ...
Returns
-------
data : dataframe
Dataframe with *x* and *y* columns, plus others for
aesthetics ... | [
"Convert",
"rect",
"data",
"to",
"polygons"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/geoms/geom_rect.py#L73-L116 |
233,477 | has2k1/plotnine | plotnine/aes.py | rename_aesthetics | def rename_aesthetics(obj):
"""
Rename aesthetics in obj
Parameters
----------
obj : dict or list
Object that contains aesthetics names
Returns
-------
obj : dict or list
Object that contains aesthetics names
"""
if isinstance(obj, dict):
for name in obj:
new_name = name.replace('colour', 'color')
if name != new_name:
obj[new_name] = obj.pop(name)
else:
obj = [name.replace('colour', 'color') for name in obj]
return obj | python | def rename_aesthetics(obj):
if isinstance(obj, dict):
for name in obj:
new_name = name.replace('colour', 'color')
if name != new_name:
obj[new_name] = obj.pop(name)
else:
obj = [name.replace('colour', 'color') for name in obj]
return obj | [
"def",
"rename_aesthetics",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"for",
"name",
"in",
"obj",
":",
"new_name",
"=",
"name",
".",
"replace",
"(",
"'colour'",
",",
"'color'",
")",
"if",
"name",
"!=",
"new_name",
"... | Rename aesthetics in obj
Parameters
----------
obj : dict or list
Object that contains aesthetics names
Returns
-------
obj : dict or list
Object that contains aesthetics names | [
"Rename",
"aesthetics",
"in",
"obj"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L144-L166 |
233,478 | has2k1/plotnine | plotnine/aes.py | get_calculated_aes | def get_calculated_aes(aesthetics):
"""
Return a list of the aesthetics that are calculated
"""
calculated_aesthetics = []
for name, value in aesthetics.items():
if is_calculated_aes(value):
calculated_aesthetics.append(name)
return calculated_aesthetics | python | def get_calculated_aes(aesthetics):
calculated_aesthetics = []
for name, value in aesthetics.items():
if is_calculated_aes(value):
calculated_aesthetics.append(name)
return calculated_aesthetics | [
"def",
"get_calculated_aes",
"(",
"aesthetics",
")",
":",
"calculated_aesthetics",
"=",
"[",
"]",
"for",
"name",
",",
"value",
"in",
"aesthetics",
".",
"items",
"(",
")",
":",
"if",
"is_calculated_aes",
"(",
"value",
")",
":",
"calculated_aesthetics",
".",
"... | Return a list of the aesthetics that are calculated | [
"Return",
"a",
"list",
"of",
"the",
"aesthetics",
"that",
"are",
"calculated"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L169-L177 |
233,479 | has2k1/plotnine | plotnine/aes.py | is_calculated_aes | def is_calculated_aes(ae):
"""
Return a True if of the aesthetics that are calculated
Parameters
----------
ae : object
Aesthetic mapping
>>> is_calculated_aes('density')
False
>>> is_calculated_aes(4)
False
>>> is_calculated_aes('..density..')
True
>>> is_calculated_aes('stat(density)')
True
>>> is_calculated_aes('stat(100*density)')
True
>>> is_calculated_aes('100*stat(density)')
True
"""
if not isinstance(ae, str):
return False
for pattern in (STAT_RE, DOTS_RE):
if pattern.search(ae):
return True
return False | python | def is_calculated_aes(ae):
if not isinstance(ae, str):
return False
for pattern in (STAT_RE, DOTS_RE):
if pattern.search(ae):
return True
return False | [
"def",
"is_calculated_aes",
"(",
"ae",
")",
":",
"if",
"not",
"isinstance",
"(",
"ae",
",",
"str",
")",
":",
"return",
"False",
"for",
"pattern",
"in",
"(",
"STAT_RE",
",",
"DOTS_RE",
")",
":",
"if",
"pattern",
".",
"search",
"(",
"ae",
")",
":",
"... | Return a True if of the aesthetics that are calculated
Parameters
----------
ae : object
Aesthetic mapping
>>> is_calculated_aes('density')
False
>>> is_calculated_aes(4)
False
>>> is_calculated_aes('..density..')
True
>>> is_calculated_aes('stat(density)')
True
>>> is_calculated_aes('stat(100*density)')
True
>>> is_calculated_aes('100*stat(density)')
True | [
"Return",
"a",
"True",
"if",
"of",
"the",
"aesthetics",
"that",
"are",
"calculated"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L180-L214 |
233,480 | has2k1/plotnine | plotnine/aes.py | strip_stat | def strip_stat(value):
"""
Remove calc function that mark calculated aesthetics
Parameters
----------
value : object
Aesthetic value. In most cases this will be a string
but other types will pass through unmodified.
Return
------
out : object
Aesthetic value with the dots removed.
>>> strip_stat('stat(density + stat(count))')
density + count
>>> strip_stat('stat(density) + 5')
density + 5
>>> strip_stat('5 + stat(func(density))')
5 + func(density)
>>> strip_stat('stat(func(density) + var1)')
func(density) + var1
>>> strip_stat('calc + var1')
calc + var1
>>> strip_stat(4)
4
"""
def strip_hanging_closing_parens(s):
"""
Remove leftover parens
"""
# Use and integer stack to track parens
# and ignore leftover closing parens
stack = 0
idx = []
for i, c in enumerate(s):
if c == '(':
stack += 1
elif c == ')':
stack -= 1
if stack < 0:
idx.append(i)
stack = 0
continue
yield c
with suppress(TypeError):
if STAT_RE.search(value):
value = re.sub(r'\bstat\(', '', value)
value = ''.join(strip_hanging_closing_parens(value))
return value | python | def strip_stat(value):
def strip_hanging_closing_parens(s):
"""
Remove leftover parens
"""
# Use and integer stack to track parens
# and ignore leftover closing parens
stack = 0
idx = []
for i, c in enumerate(s):
if c == '(':
stack += 1
elif c == ')':
stack -= 1
if stack < 0:
idx.append(i)
stack = 0
continue
yield c
with suppress(TypeError):
if STAT_RE.search(value):
value = re.sub(r'\bstat\(', '', value)
value = ''.join(strip_hanging_closing_parens(value))
return value | [
"def",
"strip_stat",
"(",
"value",
")",
":",
"def",
"strip_hanging_closing_parens",
"(",
"s",
")",
":",
"\"\"\"\n Remove leftover parens\n \"\"\"",
"# Use and integer stack to track parens",
"# and ignore leftover closing parens",
"stack",
"=",
"0",
"idx",
"=",
... | Remove calc function that mark calculated aesthetics
Parameters
----------
value : object
Aesthetic value. In most cases this will be a string
but other types will pass through unmodified.
Return
------
out : object
Aesthetic value with the dots removed.
>>> strip_stat('stat(density + stat(count))')
density + count
>>> strip_stat('stat(density) + 5')
density + 5
>>> strip_stat('5 + stat(func(density))')
5 + func(density)
>>> strip_stat('stat(func(density) + var1)')
func(density) + var1
>>> strip_stat('calc + var1')
calc + var1
>>> strip_stat(4)
4 | [
"Remove",
"calc",
"function",
"that",
"mark",
"calculated",
"aesthetics"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L234-L291 |
233,481 | has2k1/plotnine | plotnine/aes.py | is_position_aes | def is_position_aes(vars_):
"""
Figure out if an aesthetic is a position aesthetic or not
"""
try:
return all([aes_to_scale(v) in {'x', 'y'} for v in vars_])
except TypeError:
return aes_to_scale(vars_) in {'x', 'y'} | python | def is_position_aes(vars_):
try:
return all([aes_to_scale(v) in {'x', 'y'} for v in vars_])
except TypeError:
return aes_to_scale(vars_) in {'x', 'y'} | [
"def",
"is_position_aes",
"(",
"vars_",
")",
":",
"try",
":",
"return",
"all",
"(",
"[",
"aes_to_scale",
"(",
"v",
")",
"in",
"{",
"'x'",
",",
"'y'",
"}",
"for",
"v",
"in",
"vars_",
"]",
")",
"except",
"TypeError",
":",
"return",
"aes_to_scale",
"(",... | Figure out if an aesthetic is a position aesthetic or not | [
"Figure",
"out",
"if",
"an",
"aesthetic",
"is",
"a",
"position",
"aesthetic",
"or",
"not"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L343-L350 |
233,482 | has2k1/plotnine | plotnine/aes.py | make_labels | def make_labels(mapping):
"""
Convert aesthetic mapping into text labels
"""
labels = mapping.copy()
for ae in labels:
labels[ae] = strip_calculated_markers(labels[ae])
return labels | python | def make_labels(mapping):
labels = mapping.copy()
for ae in labels:
labels[ae] = strip_calculated_markers(labels[ae])
return labels | [
"def",
"make_labels",
"(",
"mapping",
")",
":",
"labels",
"=",
"mapping",
".",
"copy",
"(",
")",
"for",
"ae",
"in",
"labels",
":",
"labels",
"[",
"ae",
"]",
"=",
"strip_calculated_markers",
"(",
"labels",
"[",
"ae",
"]",
")",
"return",
"labels"
] | Convert aesthetic mapping into text labels | [
"Convert",
"aesthetic",
"mapping",
"into",
"text",
"labels"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L353-L360 |
233,483 | has2k1/plotnine | plotnine/aes.py | is_valid_aesthetic | def is_valid_aesthetic(value, ae):
"""
Return True if `value` looks valid.
Parameters
----------
value : object
Value to check
ae : str
Aesthetic name
Returns
-------
out : bool
Whether the value is of a valid looking form.
Notes
-----
There are no guarantees that he value is spot on
valid.
"""
if ae == 'linetype':
named = {'solid', 'dashed', 'dashdot', 'dotted',
'_', '--', '-.', ':', 'None', ' ', ''}
if value in named:
return True
# tuple of the form (offset, (on, off, on, off, ...))
# e.g (0, (1, 2))
conditions = [isinstance(value, tuple),
isinstance(value[0], int),
isinstance(value[1], tuple),
len(value[1]) % 2 == 0,
all(isinstance(x, int) for x in value[1])]
if all(conditions):
return True
return False
elif ae == 'shape':
if isinstance(value, str):
return True
# tuple of the form (numsides, style, angle)
# where style is in the range [0, 3]
# e.g (4, 1, 45)
conditions = [isinstance(value, tuple),
all(isinstance(x, int) for x in value),
0 <= value[1] < 3]
if all(conditions):
return True
return False
elif ae in {'color', 'fill'}:
if isinstance(value, str):
return True
with suppress(TypeError):
if (isinstance(value, (tuple, list)) and
all(0 <= x <= 1 for x in value)):
return True
return False
# For any other aesthetics we return False to allow
# for special cases to be discovered and then coded
# for appropriately.
return False | python | def is_valid_aesthetic(value, ae):
if ae == 'linetype':
named = {'solid', 'dashed', 'dashdot', 'dotted',
'_', '--', '-.', ':', 'None', ' ', ''}
if value in named:
return True
# tuple of the form (offset, (on, off, on, off, ...))
# e.g (0, (1, 2))
conditions = [isinstance(value, tuple),
isinstance(value[0], int),
isinstance(value[1], tuple),
len(value[1]) % 2 == 0,
all(isinstance(x, int) for x in value[1])]
if all(conditions):
return True
return False
elif ae == 'shape':
if isinstance(value, str):
return True
# tuple of the form (numsides, style, angle)
# where style is in the range [0, 3]
# e.g (4, 1, 45)
conditions = [isinstance(value, tuple),
all(isinstance(x, int) for x in value),
0 <= value[1] < 3]
if all(conditions):
return True
return False
elif ae in {'color', 'fill'}:
if isinstance(value, str):
return True
with suppress(TypeError):
if (isinstance(value, (tuple, list)) and
all(0 <= x <= 1 for x in value)):
return True
return False
# For any other aesthetics we return False to allow
# for special cases to be discovered and then coded
# for appropriately.
return False | [
"def",
"is_valid_aesthetic",
"(",
"value",
",",
"ae",
")",
":",
"if",
"ae",
"==",
"'linetype'",
":",
"named",
"=",
"{",
"'solid'",
",",
"'dashed'",
",",
"'dashdot'",
",",
"'dotted'",
",",
"'_'",
",",
"'--'",
",",
"'-.'",
",",
"':'",
",",
"'None'",
",... | Return True if `value` looks valid.
Parameters
----------
value : object
Value to check
ae : str
Aesthetic name
Returns
-------
out : bool
Whether the value is of a valid looking form.
Notes
-----
There are no guarantees that he value is spot on
valid. | [
"Return",
"True",
"if",
"value",
"looks",
"valid",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/aes.py#L363-L428 |
233,484 | has2k1/plotnine | plotnine/facets/facet_wrap.py | parse_wrap_facets | def parse_wrap_facets(facets):
"""
Return list of facetting variables
"""
valid_forms = ['~ var1', '~ var1 + var2']
error_msg = ("Valid formula for 'facet_wrap' look like"
" {}".format(valid_forms))
if isinstance(facets, (list, tuple)):
return facets
if not isinstance(facets, str):
raise PlotnineError(error_msg)
if '~' in facets:
variables_pattern = r'(\w+(?:\s*\+\s*\w+)*|\.)'
pattern = r'\s*~\s*{0}\s*'.format(variables_pattern)
match = re.match(pattern, facets)
if not match:
raise PlotnineError(error_msg)
facets = [var.strip() for var in match.group(1).split('+')]
elif re.match(r'\w+', facets):
# allow plain string as the variable name
facets = [facets]
else:
raise PlotnineError(error_msg)
return facets | python | def parse_wrap_facets(facets):
valid_forms = ['~ var1', '~ var1 + var2']
error_msg = ("Valid formula for 'facet_wrap' look like"
" {}".format(valid_forms))
if isinstance(facets, (list, tuple)):
return facets
if not isinstance(facets, str):
raise PlotnineError(error_msg)
if '~' in facets:
variables_pattern = r'(\w+(?:\s*\+\s*\w+)*|\.)'
pattern = r'\s*~\s*{0}\s*'.format(variables_pattern)
match = re.match(pattern, facets)
if not match:
raise PlotnineError(error_msg)
facets = [var.strip() for var in match.group(1).split('+')]
elif re.match(r'\w+', facets):
# allow plain string as the variable name
facets = [facets]
else:
raise PlotnineError(error_msg)
return facets | [
"def",
"parse_wrap_facets",
"(",
"facets",
")",
":",
"valid_forms",
"=",
"[",
"'~ var1'",
",",
"'~ var1 + var2'",
"]",
"error_msg",
"=",
"(",
"\"Valid formula for 'facet_wrap' look like\"",
"\" {}\"",
".",
"format",
"(",
"valid_forms",
")",
")",
"if",
"isinstance",
... | Return list of facetting variables | [
"Return",
"list",
"of",
"facetting",
"variables"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet_wrap.py#L256-L284 |
233,485 | has2k1/plotnine | plotnine/facets/facet_wrap.py | n2mfrow | def n2mfrow(nr_plots):
"""
Compute the rows and columns given the number
of plots.
This is a port of grDevices::n2mfrow from R
"""
if nr_plots <= 3:
nrow, ncol = nr_plots, 1
elif nr_plots <= 6:
nrow, ncol = (nr_plots + 1) // 2, 2
elif nr_plots <= 12:
nrow, ncol = (nr_plots + 2) // 3, 3
else:
nrow = int(np.ceil(np.sqrt(nr_plots)))
ncol = int(np.ceil(nr_plots/nrow))
return (nrow, ncol) | python | def n2mfrow(nr_plots):
if nr_plots <= 3:
nrow, ncol = nr_plots, 1
elif nr_plots <= 6:
nrow, ncol = (nr_plots + 1) // 2, 2
elif nr_plots <= 12:
nrow, ncol = (nr_plots + 2) // 3, 3
else:
nrow = int(np.ceil(np.sqrt(nr_plots)))
ncol = int(np.ceil(nr_plots/nrow))
return (nrow, ncol) | [
"def",
"n2mfrow",
"(",
"nr_plots",
")",
":",
"if",
"nr_plots",
"<=",
"3",
":",
"nrow",
",",
"ncol",
"=",
"nr_plots",
",",
"1",
"elif",
"nr_plots",
"<=",
"6",
":",
"nrow",
",",
"ncol",
"=",
"(",
"nr_plots",
"+",
"1",
")",
"//",
"2",
",",
"2",
"e... | Compute the rows and columns given the number
of plots.
This is a port of grDevices::n2mfrow from R | [
"Compute",
"the",
"rows",
"and",
"columns",
"given",
"the",
"number",
"of",
"plots",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet_wrap.py#L302-L318 |
233,486 | has2k1/plotnine | plotnine/facets/facet_wrap.py | facet_wrap.spaceout_and_resize_panels | def spaceout_and_resize_panels(self):
"""
Adjust the spacing between the panels and resize them
to meet the aspect ratio
"""
ncol = self.ncol
nrow = self.nrow
figure = self.figure
theme = self.theme
get_property = theme.themeables.property
left = figure.subplotpars.left
right = figure.subplotpars.right
top = figure.subplotpars.top
bottom = figure.subplotpars.bottom
top_strip_height = self.strip_size('top')
W, H = figure.get_size_inches()
try:
spacing_x = get_property('panel_spacing_x')
except KeyError:
spacing_x = 0.1
try:
spacing_y = get_property('panel_spacing_y')
except KeyError:
spacing_y = 0.1
try:
aspect_ratio = get_property('aspect_ratio')
except KeyError:
# If the panels have different limits the coordinates
# cannot compute a common aspect ratio
if not self.free['x'] and not self.free['y']:
aspect_ratio = self.coordinates.aspect(
self.layout.panel_params[0])
else:
aspect_ratio = None
if theme.themeables.is_blank('strip_text_x'):
top_strip_height = 0
# Account for the vertical sliding of the strip if any
with suppress(KeyError):
strip_margin_x = get_property('strip_margin_x')
top_strip_height *= (1 + strip_margin_x)
# The goal is to have equal spacing along the vertical
# and the horizontal. We use the wspace and compute
# the appropriate hspace. It would be a lot easier if
# MPL had a better layout manager.
# width of axes and height of axes
w = ((right-left)*W - spacing_x*(ncol-1)) / ncol
h = ((top-bottom)*H - (spacing_y+top_strip_height)*(nrow-1)) / nrow
# aspect ratio changes the size of the figure
if aspect_ratio is not None:
h = w*aspect_ratio
H = (h*nrow + (spacing_y+top_strip_height)*(nrow-1)) / \
(top-bottom)
figure.set_figheight(H)
# spacing
wspace = spacing_x/w
hspace = (spacing_y + top_strip_height) / h
figure.subplots_adjust(wspace=wspace, hspace=hspace) | python | def spaceout_and_resize_panels(self):
ncol = self.ncol
nrow = self.nrow
figure = self.figure
theme = self.theme
get_property = theme.themeables.property
left = figure.subplotpars.left
right = figure.subplotpars.right
top = figure.subplotpars.top
bottom = figure.subplotpars.bottom
top_strip_height = self.strip_size('top')
W, H = figure.get_size_inches()
try:
spacing_x = get_property('panel_spacing_x')
except KeyError:
spacing_x = 0.1
try:
spacing_y = get_property('panel_spacing_y')
except KeyError:
spacing_y = 0.1
try:
aspect_ratio = get_property('aspect_ratio')
except KeyError:
# If the panels have different limits the coordinates
# cannot compute a common aspect ratio
if not self.free['x'] and not self.free['y']:
aspect_ratio = self.coordinates.aspect(
self.layout.panel_params[0])
else:
aspect_ratio = None
if theme.themeables.is_blank('strip_text_x'):
top_strip_height = 0
# Account for the vertical sliding of the strip if any
with suppress(KeyError):
strip_margin_x = get_property('strip_margin_x')
top_strip_height *= (1 + strip_margin_x)
# The goal is to have equal spacing along the vertical
# and the horizontal. We use the wspace and compute
# the appropriate hspace. It would be a lot easier if
# MPL had a better layout manager.
# width of axes and height of axes
w = ((right-left)*W - spacing_x*(ncol-1)) / ncol
h = ((top-bottom)*H - (spacing_y+top_strip_height)*(nrow-1)) / nrow
# aspect ratio changes the size of the figure
if aspect_ratio is not None:
h = w*aspect_ratio
H = (h*nrow + (spacing_y+top_strip_height)*(nrow-1)) / \
(top-bottom)
figure.set_figheight(H)
# spacing
wspace = spacing_x/w
hspace = (spacing_y + top_strip_height) / h
figure.subplots_adjust(wspace=wspace, hspace=hspace) | [
"def",
"spaceout_and_resize_panels",
"(",
"self",
")",
":",
"ncol",
"=",
"self",
".",
"ncol",
"nrow",
"=",
"self",
".",
"nrow",
"figure",
"=",
"self",
".",
"figure",
"theme",
"=",
"self",
".",
"theme",
"get_property",
"=",
"theme",
".",
"themeables",
"."... | Adjust the spacing between the panels and resize them
to meet the aspect ratio | [
"Adjust",
"the",
"spacing",
"between",
"the",
"panels",
"and",
"resize",
"them",
"to",
"meet",
"the",
"aspect",
"ratio"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/facets/facet_wrap.py#L149-L215 |
233,487 | has2k1/plotnine | plotnine/themes/elements.py | Margin.get_as | def get_as(self, key, units='pt'):
"""
Return key in given units
"""
dpi = 72
size = self.element.properties.get('size', 0)
value = self[key]
functions = {
'pt-lines': lambda x: x/size,
'pt-in': lambda x: x/dpi,
'lines-pt': lambda x: x*size,
'lines-in': lambda x: x*size/dpi,
'in-pt': lambda x: x*dpi,
'in-lines': lambda x: x*dpi/size
}
if self['units'] != units:
conversion = '{}-{}'.format(self['units'], units)
try:
value = functions[conversion](value)
except ZeroDivisionError:
value = 0
return value | python | def get_as(self, key, units='pt'):
dpi = 72
size = self.element.properties.get('size', 0)
value = self[key]
functions = {
'pt-lines': lambda x: x/size,
'pt-in': lambda x: x/dpi,
'lines-pt': lambda x: x*size,
'lines-in': lambda x: x*size/dpi,
'in-pt': lambda x: x*dpi,
'in-lines': lambda x: x*dpi/size
}
if self['units'] != units:
conversion = '{}-{}'.format(self['units'], units)
try:
value = functions[conversion](value)
except ZeroDivisionError:
value = 0
return value | [
"def",
"get_as",
"(",
"self",
",",
"key",
",",
"units",
"=",
"'pt'",
")",
":",
"dpi",
"=",
"72",
"size",
"=",
"self",
".",
"element",
".",
"properties",
".",
"get",
"(",
"'size'",
",",
"0",
")",
"value",
"=",
"self",
"[",
"key",
"]",
"functions",... | Return key in given units | [
"Return",
"key",
"in",
"given",
"units"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/themes/elements.py#L223-L247 |
233,488 | has2k1/plotnine | plotnine/layer.py | discrete_columns | def discrete_columns(df, ignore):
"""
Return a list of the discrete columns in the
dataframe `df`. `ignore` is a list|set|tuple with the
names of the columns to skip.
"""
lst = []
for col in df:
if array_kind.discrete(df[col]) and (col not in ignore):
# Some columns are represented as object dtype
# but may have compound structures as values.
try:
hash(df[col].iloc[0])
except TypeError:
continue
lst.append(col)
return lst | python | def discrete_columns(df, ignore):
lst = []
for col in df:
if array_kind.discrete(df[col]) and (col not in ignore):
# Some columns are represented as object dtype
# but may have compound structures as values.
try:
hash(df[col].iloc[0])
except TypeError:
continue
lst.append(col)
return lst | [
"def",
"discrete_columns",
"(",
"df",
",",
"ignore",
")",
":",
"lst",
"=",
"[",
"]",
"for",
"col",
"in",
"df",
":",
"if",
"array_kind",
".",
"discrete",
"(",
"df",
"[",
"col",
"]",
")",
"and",
"(",
"col",
"not",
"in",
"ignore",
")",
":",
"# Some ... | Return a list of the discrete columns in the
dataframe `df`. `ignore` is a list|set|tuple with the
names of the columns to skip. | [
"Return",
"a",
"list",
"of",
"the",
"discrete",
"columns",
"in",
"the",
"dataframe",
"df",
".",
"ignore",
"is",
"a",
"list|set|tuple",
"with",
"the",
"names",
"of",
"the",
"columns",
"to",
"skip",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L490-L506 |
233,489 | has2k1/plotnine | plotnine/layer.py | is_known_scalar | def is_known_scalar(value):
"""
Return True if value is a type we expect in a dataframe
"""
def _is_datetime_or_timedelta(value):
# Using pandas.Series helps catch python, numpy and pandas
# versions of these types
return pd.Series(value).dtype.kind in ('M', 'm')
return not np.iterable(value) and (isinstance(value, numbers.Number) or
_is_datetime_or_timedelta(value)) | python | def is_known_scalar(value):
def _is_datetime_or_timedelta(value):
# Using pandas.Series helps catch python, numpy and pandas
# versions of these types
return pd.Series(value).dtype.kind in ('M', 'm')
return not np.iterable(value) and (isinstance(value, numbers.Number) or
_is_datetime_or_timedelta(value)) | [
"def",
"is_known_scalar",
"(",
"value",
")",
":",
"def",
"_is_datetime_or_timedelta",
"(",
"value",
")",
":",
"# Using pandas.Series helps catch python, numpy and pandas",
"# versions of these types",
"return",
"pd",
".",
"Series",
"(",
"value",
")",
".",
"dtype",
".",
... | Return True if value is a type we expect in a dataframe | [
"Return",
"True",
"if",
"value",
"is",
"a",
"type",
"we",
"expect",
"in",
"a",
"dataframe"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L509-L519 |
233,490 | has2k1/plotnine | plotnine/layer.py | layer.generate_data | def generate_data(self, plot_data):
"""
Generate data to be used by this layer
Parameters
----------
plot_data : dataframe
ggplot object data
"""
# Each layer that does not have data gets a copy of
# of the ggplot.data. If the has data it is replaced
# by copy so that we do not alter the users data
if self.data is None:
self.data = plot_data.copy()
elif hasattr(self.data, '__call__'):
self.data = self.data(plot_data)
if not isinstance(self.data, pd.DataFrame):
raise PlotnineError(
"Data function must return a dataframe")
else:
self.data = self.data.copy() | python | def generate_data(self, plot_data):
# Each layer that does not have data gets a copy of
# of the ggplot.data. If the has data it is replaced
# by copy so that we do not alter the users data
if self.data is None:
self.data = plot_data.copy()
elif hasattr(self.data, '__call__'):
self.data = self.data(plot_data)
if not isinstance(self.data, pd.DataFrame):
raise PlotnineError(
"Data function must return a dataframe")
else:
self.data = self.data.copy() | [
"def",
"generate_data",
"(",
"self",
",",
"plot_data",
")",
":",
"# Each layer that does not have data gets a copy of",
"# of the ggplot.data. If the has data it is replaced",
"# by copy so that we do not alter the users data",
"if",
"self",
".",
"data",
"is",
"None",
":",
"self"... | Generate data to be used by this layer
Parameters
----------
plot_data : dataframe
ggplot object data | [
"Generate",
"data",
"to",
"be",
"used",
"by",
"this",
"layer"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L229-L249 |
233,491 | has2k1/plotnine | plotnine/layer.py | layer.layer_mapping | def layer_mapping(self, mapping):
"""
Return the mappings that are active in this layer
Parameters
----------
mapping : aes
mappings in the ggplot call
Notes
-----
Once computed the layer mappings are also stored
in self._active_mapping
"""
# For certain geoms, it is useful to be able to
# ignore the default aesthetics and only use those
# set in the layer
if self.inherit_aes:
aesthetics = defaults(self.mapping, mapping)
else:
aesthetics = self.mapping
# drop aesthetic parameters or the calculated aesthetics
calculated = set(get_calculated_aes(aesthetics))
d = dict((ae, v) for ae, v in aesthetics.items()
if (ae not in self.geom.aes_params) and
(ae not in calculated))
self._active_mapping = aes(**d)
return self._active_mapping | python | def layer_mapping(self, mapping):
# For certain geoms, it is useful to be able to
# ignore the default aesthetics and only use those
# set in the layer
if self.inherit_aes:
aesthetics = defaults(self.mapping, mapping)
else:
aesthetics = self.mapping
# drop aesthetic parameters or the calculated aesthetics
calculated = set(get_calculated_aes(aesthetics))
d = dict((ae, v) for ae, v in aesthetics.items()
if (ae not in self.geom.aes_params) and
(ae not in calculated))
self._active_mapping = aes(**d)
return self._active_mapping | [
"def",
"layer_mapping",
"(",
"self",
",",
"mapping",
")",
":",
"# For certain geoms, it is useful to be able to",
"# ignore the default aesthetics and only use those",
"# set in the layer",
"if",
"self",
".",
"inherit_aes",
":",
"aesthetics",
"=",
"defaults",
"(",
"self",
"... | Return the mappings that are active in this layer
Parameters
----------
mapping : aes
mappings in the ggplot call
Notes
-----
Once computed the layer mappings are also stored
in self._active_mapping | [
"Return",
"the",
"mappings",
"that",
"are",
"active",
"in",
"this",
"layer"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L251-L279 |
233,492 | has2k1/plotnine | plotnine/layer.py | layer.compute_aesthetics | def compute_aesthetics(self, plot):
"""
Return a dataframe where the columns match the
aesthetic mappings.
Transformations like 'factor(cyl)' and other
expression evaluation are made in here
"""
data = self.data
aesthetics = self.layer_mapping(plot.mapping)
# Override grouping if set in layer.
with suppress(KeyError):
aesthetics['group'] = self.geom.aes_params['group']
env = EvalEnvironment.capture(eval_env=plot.environment)
env = env.with_outer_namespace({'factor': pd.Categorical})
# Using `type` preserves the subclass of pd.DataFrame
evaled = type(data)(index=data.index)
# If a column name is not in the data, it is evaluated/transformed
# in the environment of the call to ggplot
for ae, col in aesthetics.items():
if isinstance(col, str):
if col in data:
evaled[ae] = data[col]
else:
try:
new_val = env.eval(col, inner_namespace=data)
except Exception as e:
raise PlotnineError(
_TPL_EVAL_FAIL.format(ae, col, str(e)))
try:
evaled[ae] = new_val
except Exception as e:
raise PlotnineError(
_TPL_BAD_EVAL_TYPE.format(
ae, col, str(type(new_val)), str(e)))
elif pdtypes.is_list_like(col):
n = len(col)
if len(data) and n != len(data) and n != 1:
raise PlotnineError(
"Aesthetics must either be length one, " +
"or the same length as the data")
# An empty dataframe does not admit a scalar value
elif len(evaled) and n == 1:
col = col[0]
evaled[ae] = col
elif is_known_scalar(col):
if not len(evaled):
col = [col]
evaled[ae] = col
else:
msg = "Do not know how to deal with aesthetic '{}'"
raise PlotnineError(msg.format(ae))
evaled_aes = aes(**dict((col, col) for col in evaled))
plot.scales.add_defaults(evaled, evaled_aes)
if len(data) == 0 and len(evaled) > 0:
# No data, and vectors suppled to aesthetics
evaled['PANEL'] = 1
else:
evaled['PANEL'] = data['PANEL']
self.data = add_group(evaled) | python | def compute_aesthetics(self, plot):
data = self.data
aesthetics = self.layer_mapping(plot.mapping)
# Override grouping if set in layer.
with suppress(KeyError):
aesthetics['group'] = self.geom.aes_params['group']
env = EvalEnvironment.capture(eval_env=plot.environment)
env = env.with_outer_namespace({'factor': pd.Categorical})
# Using `type` preserves the subclass of pd.DataFrame
evaled = type(data)(index=data.index)
# If a column name is not in the data, it is evaluated/transformed
# in the environment of the call to ggplot
for ae, col in aesthetics.items():
if isinstance(col, str):
if col in data:
evaled[ae] = data[col]
else:
try:
new_val = env.eval(col, inner_namespace=data)
except Exception as e:
raise PlotnineError(
_TPL_EVAL_FAIL.format(ae, col, str(e)))
try:
evaled[ae] = new_val
except Exception as e:
raise PlotnineError(
_TPL_BAD_EVAL_TYPE.format(
ae, col, str(type(new_val)), str(e)))
elif pdtypes.is_list_like(col):
n = len(col)
if len(data) and n != len(data) and n != 1:
raise PlotnineError(
"Aesthetics must either be length one, " +
"or the same length as the data")
# An empty dataframe does not admit a scalar value
elif len(evaled) and n == 1:
col = col[0]
evaled[ae] = col
elif is_known_scalar(col):
if not len(evaled):
col = [col]
evaled[ae] = col
else:
msg = "Do not know how to deal with aesthetic '{}'"
raise PlotnineError(msg.format(ae))
evaled_aes = aes(**dict((col, col) for col in evaled))
plot.scales.add_defaults(evaled, evaled_aes)
if len(data) == 0 and len(evaled) > 0:
# No data, and vectors suppled to aesthetics
evaled['PANEL'] = 1
else:
evaled['PANEL'] = data['PANEL']
self.data = add_group(evaled) | [
"def",
"compute_aesthetics",
"(",
"self",
",",
"plot",
")",
":",
"data",
"=",
"self",
".",
"data",
"aesthetics",
"=",
"self",
".",
"layer_mapping",
"(",
"plot",
".",
"mapping",
")",
"# Override grouping if set in layer.",
"with",
"suppress",
"(",
"KeyError",
"... | Return a dataframe where the columns match the
aesthetic mappings.
Transformations like 'factor(cyl)' and other
expression evaluation are made in here | [
"Return",
"a",
"dataframe",
"where",
"the",
"columns",
"match",
"the",
"aesthetic",
"mappings",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L281-L348 |
233,493 | has2k1/plotnine | plotnine/layer.py | layer.compute_statistic | def compute_statistic(self, layout):
"""
Compute & return statistics for this layer
"""
data = self.data
if not len(data):
return type(data)()
params = self.stat.setup_params(data)
data = self.stat.use_defaults(data)
data = self.stat.setup_data(data)
data = self.stat.compute_layer(data, params, layout)
self.data = data | python | def compute_statistic(self, layout):
data = self.data
if not len(data):
return type(data)()
params = self.stat.setup_params(data)
data = self.stat.use_defaults(data)
data = self.stat.setup_data(data)
data = self.stat.compute_layer(data, params, layout)
self.data = data | [
"def",
"compute_statistic",
"(",
"self",
",",
"layout",
")",
":",
"data",
"=",
"self",
".",
"data",
"if",
"not",
"len",
"(",
"data",
")",
":",
"return",
"type",
"(",
"data",
")",
"(",
")",
"params",
"=",
"self",
".",
"stat",
".",
"setup_params",
"(... | Compute & return statistics for this layer | [
"Compute",
"&",
"return",
"statistics",
"for",
"this",
"layer"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L350-L362 |
233,494 | has2k1/plotnine | plotnine/layer.py | layer.map_statistic | def map_statistic(self, plot):
"""
Mapping aesthetics to computed statistics
"""
data = self.data
if not len(data):
return type(data)()
# Assemble aesthetics from layer, plot and stat mappings
aesthetics = deepcopy(self.mapping)
if self.inherit_aes:
aesthetics = defaults(aesthetics, plot.mapping)
aesthetics = defaults(aesthetics, self.stat.DEFAULT_AES)
# The new aesthetics are those that the stat calculates
# and have been mapped to with dot dot notation
# e.g aes(y='..count..'), y is the new aesthetic and
# 'count' is the computed column in data
new = {} # {'aesthetic_name': 'calculated_stat'}
stat_data = type(data)()
stat_namespace = dict(stat=stat)
env = plot.environment.with_outer_namespace(stat_namespace)
for ae in get_calculated_aes(aesthetics):
new[ae] = strip_calculated_markers(aesthetics[ae])
# In conjuction with the pd.concat at the end,
# be careful not to create duplicate columns
# for cases like y='..y..'
if new[ae] != ae:
stat_data[ae] = env.eval(
new[ae], inner_namespace=data)
if not new:
return
# (see stat_spoke for one exception)
if self.stat.retransform:
stat_data = plot.scales.transform_df(stat_data)
# When there are duplicate columns, we use the computed
# ones in stat_data
columns = data.columns.difference(stat_data.columns)
self.data = pd.concat([data[columns], stat_data], axis=1)
# Add any new scales, if needed
plot.scales.add_defaults(self.data, new) | python | def map_statistic(self, plot):
data = self.data
if not len(data):
return type(data)()
# Assemble aesthetics from layer, plot and stat mappings
aesthetics = deepcopy(self.mapping)
if self.inherit_aes:
aesthetics = defaults(aesthetics, plot.mapping)
aesthetics = defaults(aesthetics, self.stat.DEFAULT_AES)
# The new aesthetics are those that the stat calculates
# and have been mapped to with dot dot notation
# e.g aes(y='..count..'), y is the new aesthetic and
# 'count' is the computed column in data
new = {} # {'aesthetic_name': 'calculated_stat'}
stat_data = type(data)()
stat_namespace = dict(stat=stat)
env = plot.environment.with_outer_namespace(stat_namespace)
for ae in get_calculated_aes(aesthetics):
new[ae] = strip_calculated_markers(aesthetics[ae])
# In conjuction with the pd.concat at the end,
# be careful not to create duplicate columns
# for cases like y='..y..'
if new[ae] != ae:
stat_data[ae] = env.eval(
new[ae], inner_namespace=data)
if not new:
return
# (see stat_spoke for one exception)
if self.stat.retransform:
stat_data = plot.scales.transform_df(stat_data)
# When there are duplicate columns, we use the computed
# ones in stat_data
columns = data.columns.difference(stat_data.columns)
self.data = pd.concat([data[columns], stat_data], axis=1)
# Add any new scales, if needed
plot.scales.add_defaults(self.data, new) | [
"def",
"map_statistic",
"(",
"self",
",",
"plot",
")",
":",
"data",
"=",
"self",
".",
"data",
"if",
"not",
"len",
"(",
"data",
")",
":",
"return",
"type",
"(",
"data",
")",
"(",
")",
"# Assemble aesthetics from layer, plot and stat mappings",
"aesthetics",
"... | Mapping aesthetics to computed statistics | [
"Mapping",
"aesthetics",
"to",
"computed",
"statistics"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L364-L409 |
233,495 | has2k1/plotnine | plotnine/layer.py | layer.compute_position | def compute_position(self, layout):
"""
Compute the position of each geometric object
in concert with the other objects in the panel
"""
params = self.position.setup_params(self.data)
data = self.position.setup_data(self.data, params)
data = self.position.compute_layer(data, params, layout)
self.data = data | python | def compute_position(self, layout):
params = self.position.setup_params(self.data)
data = self.position.setup_data(self.data, params)
data = self.position.compute_layer(data, params, layout)
self.data = data | [
"def",
"compute_position",
"(",
"self",
",",
"layout",
")",
":",
"params",
"=",
"self",
".",
"position",
".",
"setup_params",
"(",
"self",
".",
"data",
")",
"data",
"=",
"self",
".",
"position",
".",
"setup_data",
"(",
"self",
".",
"data",
",",
"params... | Compute the position of each geometric object
in concert with the other objects in the panel | [
"Compute",
"the",
"position",
"of",
"each",
"geometric",
"object",
"in",
"concert",
"with",
"the",
"other",
"objects",
"in",
"the",
"panel"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/layer.py#L428-L436 |
233,496 | has2k1/plotnine | plotnine/scales/range.py | RangeContinuous.train | def train(self, x):
"""
Train continuous range
"""
self.range = scale_continuous.train(x, self.range) | python | def train(self, x):
self.range = scale_continuous.train(x, self.range) | [
"def",
"train",
"(",
"self",
",",
"x",
")",
":",
"self",
".",
"range",
"=",
"scale_continuous",
".",
"train",
"(",
"x",
",",
"self",
".",
"range",
")"
] | Train continuous range | [
"Train",
"continuous",
"range"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/range.py#L28-L32 |
233,497 | has2k1/plotnine | plotnine/scales/range.py | RangeDiscrete.train | def train(self, x, drop=False, na_rm=False):
"""
Train discrete range
"""
self.range = scale_discrete.train(x, self.range, drop, na_rm=na_rm) | python | def train(self, x, drop=False, na_rm=False):
self.range = scale_discrete.train(x, self.range, drop, na_rm=na_rm) | [
"def",
"train",
"(",
"self",
",",
"x",
",",
"drop",
"=",
"False",
",",
"na_rm",
"=",
"False",
")",
":",
"self",
".",
"range",
"=",
"scale_discrete",
".",
"train",
"(",
"x",
",",
"self",
".",
"range",
",",
"drop",
",",
"na_rm",
"=",
"na_rm",
")"
] | Train discrete range | [
"Train",
"discrete",
"range"
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/scales/range.py#L39-L43 |
233,498 | has2k1/plotnine | plotnine/utils.py | _margins | def _margins(vars, margins=True):
"""
Figure out margining variables.
Given the variables that form the rows and
columns, and a set of desired margins, works
out which ones are possible. Variables that
can't be margined over are dropped silently.
Parameters
----------
vars : list
variable names for rows and columns
margins : bool | list
If true, margins over all vars, otherwise
only those listed
Return
------
out : list
All the margins to create.
"""
if margins is False:
return []
def fn(_vars):
"The margin variables for a given row or column"
# The first item is and empty list for no margins
dim_margins = [[]]
# for each wanted variable, couple it with
# all variables to the right
for i, u in enumerate(_vars):
if margins is True or u in margins:
lst = [u] + [v for v in _vars[i+1:]]
dim_margins.append(lst)
return dim_margins
# Margin variables for rows and columns
row_margins = fn(vars[0])
col_margins = fn(vars[1])
# Cross the two
lst = list(itertools.product(col_margins, row_margins))
# Clean up -- merge the row and column variables
pretty = []
for c, r in lst:
pretty.append(r + c)
return pretty | python | def _margins(vars, margins=True):
if margins is False:
return []
def fn(_vars):
"The margin variables for a given row or column"
# The first item is and empty list for no margins
dim_margins = [[]]
# for each wanted variable, couple it with
# all variables to the right
for i, u in enumerate(_vars):
if margins is True or u in margins:
lst = [u] + [v for v in _vars[i+1:]]
dim_margins.append(lst)
return dim_margins
# Margin variables for rows and columns
row_margins = fn(vars[0])
col_margins = fn(vars[1])
# Cross the two
lst = list(itertools.product(col_margins, row_margins))
# Clean up -- merge the row and column variables
pretty = []
for c, r in lst:
pretty.append(r + c)
return pretty | [
"def",
"_margins",
"(",
"vars",
",",
"margins",
"=",
"True",
")",
":",
"if",
"margins",
"is",
"False",
":",
"return",
"[",
"]",
"def",
"fn",
"(",
"_vars",
")",
":",
"\"The margin variables for a given row or column\"",
"# The first item is and empty list for no marg... | Figure out margining variables.
Given the variables that form the rows and
columns, and a set of desired margins, works
out which ones are possible. Variables that
can't be margined over are dropped silently.
Parameters
----------
vars : list
variable names for rows and columns
margins : bool | list
If true, margins over all vars, otherwise
only those listed
Return
------
out : list
All the margins to create. | [
"Figure",
"out",
"margining",
"variables",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L143-L191 |
233,499 | has2k1/plotnine | plotnine/utils.py | add_margins | def add_margins(df, vars, margins=True):
"""
Add margins to a data frame.
All margining variables will be converted to factors.
Parameters
----------
df : dataframe
input data frame
vars : list
a list of 2 lists | tuples vectors giving the
variables in each dimension
margins : bool | list
variable names to compute margins for.
True will compute all possible margins.
"""
margin_vars = _margins(vars, margins)
if not margin_vars:
return df
# create margin dataframes
margin_dfs = [df]
for vlst in margin_vars[1:]:
dfx = df.copy()
for v in vlst:
dfx.loc[0:, v] = '(all)'
margin_dfs.append(dfx)
merged = pd.concat(margin_dfs, axis=0)
merged.reset_index(drop=True, inplace=True)
# All margin columns become categoricals. The margin indicator
# (all) needs to be added as the last level of the categories.
categories = {}
for v in itertools.chain(*vars):
col = df[v]
if not pdtypes.is_categorical_dtype(df[v].dtype):
col = pd.Categorical(df[v])
categories[v] = col.categories
if '(all)' not in categories[v]:
categories[v] = categories[v].insert(
len(categories[v]), '(all)')
for v in merged.columns.intersection(set(categories)):
merged[v] = merged[v].astype(
pdtypes.CategoricalDtype(categories[v]))
return merged | python | def add_margins(df, vars, margins=True):
margin_vars = _margins(vars, margins)
if not margin_vars:
return df
# create margin dataframes
margin_dfs = [df]
for vlst in margin_vars[1:]:
dfx = df.copy()
for v in vlst:
dfx.loc[0:, v] = '(all)'
margin_dfs.append(dfx)
merged = pd.concat(margin_dfs, axis=0)
merged.reset_index(drop=True, inplace=True)
# All margin columns become categoricals. The margin indicator
# (all) needs to be added as the last level of the categories.
categories = {}
for v in itertools.chain(*vars):
col = df[v]
if not pdtypes.is_categorical_dtype(df[v].dtype):
col = pd.Categorical(df[v])
categories[v] = col.categories
if '(all)' not in categories[v]:
categories[v] = categories[v].insert(
len(categories[v]), '(all)')
for v in merged.columns.intersection(set(categories)):
merged[v] = merged[v].astype(
pdtypes.CategoricalDtype(categories[v]))
return merged | [
"def",
"add_margins",
"(",
"df",
",",
"vars",
",",
"margins",
"=",
"True",
")",
":",
"margin_vars",
"=",
"_margins",
"(",
"vars",
",",
"margins",
")",
"if",
"not",
"margin_vars",
":",
"return",
"df",
"# create margin dataframes",
"margin_dfs",
"=",
"[",
"d... | Add margins to a data frame.
All margining variables will be converted to factors.
Parameters
----------
df : dataframe
input data frame
vars : list
a list of 2 lists | tuples vectors giving the
variables in each dimension
margins : bool | list
variable names to compute margins for.
True will compute all possible margins. | [
"Add",
"margins",
"to",
"a",
"data",
"frame",
"."
] | 566e579af705367e584fb27a74e6c5199624ca89 | https://github.com/has2k1/plotnine/blob/566e579af705367e584fb27a74e6c5199624ca89/plotnine/utils.py#L194-L244 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.