index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
18,570
traceback2
extract_tb
Return list of up to limit pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None.
def extract_tb(tb, limit=None): """Return list of up to limit pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading and trailing whitespace stripped; if the source is not available it is None. """ return StackSummary.extract(walk_tb(tb), limit=limit)
(tb, limit=None)
18,572
traceback2
format_exception
Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception().
def format_exception(etype, value, tb, limit=None, chain=True): """Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception(). """ # format_exception has ignored etype for some time, and code such as cgitb # passes in bogus values as a result. For compatibility with such code we # ignore it here (rather than in the new TracebackException API). return list(TracebackException( type(value), value, tb, limit=limit).format(chain=chain))
(etype, value, tb, limit=None, chain=True)
18,573
traceback2
format_exception_only
Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the list.
def format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the list. """ return list(TracebackException(etype, value, None).format_exception_only())
(etype, value)
18,574
traceback2
format_list
Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None.
def format_list(extracted_list): """Format a list of traceback entry tuples for printing. Given a list of tuples as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None. """ return StackSummary.from_list(extracted_list).format()
(extracted_list)
18,575
traceback2
format_stack
Shorthand for 'format_list(extract_stack(f, limit))'.
def format_stack(f=None, limit=None): """Shorthand for 'format_list(extract_stack(f, limit))'.""" return format_list(extract_stack(f, limit=limit))
(f=None, limit=None)
18,576
traceback2
format_tb
A shorthand for 'format_list(extract_tb(tb, limit))'.
def format_tb(tb, limit=None): """A shorthand for 'format_list(extract_tb(tb, limit))'.""" return extract_tb(tb, limit=limit).format()
(tb, limit=None)
18,580
traceback2
print_exception
Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate position of the error.
def print_exception(etype, value, tb, limit=None, file=None, chain=True): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate position of the error. """ # format_exception has ignored etype for some time, and code such as cgitb # passes in bogus values as a result. For compatibility with such code we # ignore it here (rather than in the new TracebackException API). if file is None: file = sys.stderr for line in TracebackException( type(value), value, tb, limit=limit).format(chain=chain): file.write(line)
(etype, value, tb, limit=None, file=None, chain=True)
18,581
traceback2
print_last
This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.
def print_last(limit=None, file=None, chain=True): """This is a shorthand for 'print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)'.""" if not hasattr(sys, "last_type"): raise ValueError("no last exception") print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain)
(limit=None, file=None, chain=True)
18,582
traceback2
print_list
Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.
def print_list(extracted_list, file=None): """Print the list of tuples as returned by extract_tb() or extract_stack() as a formatted stack trace to the given file.""" if file is None: file = sys.stderr for item in StackSummary.from_list(extracted_list).format(): file.write(item)
(extracted_list, file=None)
18,583
traceback2
print_stack
Print a stack trace from its invocation point. The optional 'f' argument can be used to specify an alternate stack frame at which to start. The optional 'limit' and 'file' arguments have the same meaning as for print_exception().
def print_stack(f=None, limit=None, file=None): """Print a stack trace from its invocation point. The optional 'f' argument can be used to specify an alternate stack frame at which to start. The optional 'limit' and 'file' arguments have the same meaning as for print_exception(). """ print_list(extract_stack(f, limit=limit), file=file)
(f=None, limit=None, file=None)
18,584
traceback2
print_tb
Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method.
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method. """ print_list(extract_tb(tb, limit=limit), file=file)
(tb, limit=None, file=None)
18,586
six
u
Text literal
def u(s): return s
(s)
18,587
traceback2
walk_stack
Walk a stack yielding the frame and line number for each frame. This will follow f.f_back from the given frame. If no frame is given, the current stack is used. Usually used with StackSummary.extract.
def walk_stack(f): """Walk a stack yielding the frame and line number for each frame. This will follow f.f_back from the given frame. If no frame is given, the current stack is used. Usually used with StackSummary.extract. """ if f is None: f = sys._getframe().f_back.f_back while f is not None: yield f, f.f_lineno f = f.f_back
(f)
18,588
traceback2
walk_tb
Walk a traceback yielding the frame and line number for each frame. This will follow tb.tb_next (and thus is in the opposite order to walk_stack). Usually used with StackSummary.extract.
def walk_tb(tb): """Walk a traceback yielding the frame and line number for each frame. This will follow tb.tb_next (and thus is in the opposite order to walk_stack). Usually used with StackSummary.extract. """ while tb is not None: yield tb.tb_frame, tb.tb_lineno tb = tb.tb_next
(tb)
18,589
pygal.graph.bar
Bar
Bar graph class
class Bar(Graph): """Bar graph class""" _series_margin = .06 _serie_margin = .06 def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal bar drawing function""" width = (self.view.x(1) - self.view.x(0)) / self._len x, y = self.view((x, y)) series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin width /= self._order if self.horizontal: serie_index = self._order - serie.index - 1 else: serie_index = serie.index x += serie_index * width serie_margin = width * self._serie_margin x += serie_margin width -= 2 * serie_margin height = self.view.y(zero) - y r = serie.rounded_bars * 1 if serie.rounded_bars else 0 alter( self.svg.transposable_node( parent, 'rect', x=x, y=y, rx=r, ry=r, width=width, height=height, class_='rect reactive tooltip-trigger' ), serie.metadata.get(i) ) return x, y, width, height def _tooltip_and_print_values( self, serie_node, serie, parent, i, val, metadata, x, y, width, height ): transpose = swap if self.horizontal else ident x_center, y_center = transpose((x + width / 2, y + height / 2)) x_top, y_top = transpose((x + width, y + height)) x_bottom, y_bottom = transpose((x, y)) if self._dual: v = serie.values[i][0] else: v = serie.values[i] sign = -1 if v < self.zero else 1 self._tooltip_data( parent, val, x_center, y_center, "centered", self._get_x_label(i) ) if self.print_values_position == 'top': if self.horizontal: x = x_bottom + sign * self.style.value_font_size / 2 y = y_center else: x = x_center y = y_bottom - sign * self.style.value_font_size / 2 elif self.print_values_position == 'bottom': if self.horizontal: x = x_top + sign * self.style.value_font_size / 2 y = y_center else: x = x_center y = y_top - sign * self.style.value_font_size / 2 else: x = x_center y = y_center self._static_value(serie_node, val, x, y, metadata, "middle") def bar(self, serie, rescale=False): """Draw a bar graph for a serie""" serie_node = self.svg.serie(serie) bars = self.svg.node(serie_node['plot'], class_="bars") if rescale and self.secondary_series: points = self._rescale(serie.points) else: points = serie.points for i, (x, y) in enumerate(points): if None in (x, y) or (self.logarithmic and y <= 0): continue metadata = serie.metadata.get(i) val = self._format(serie, i) bar = decorate( self.svg, self.svg.node(bars, class_='bar'), metadata ) x_, y_, width, height = self._bar( serie, bar, x, y, i, self.zero, secondary=rescale ) self._confidence_interval( serie_node['overlay'], x_ + width / 2, y_, serie.values[i], metadata ) self._tooltip_and_print_values( serie_node, serie, bar, i, val, metadata, x_, y_, width, height ) def _compute(self): """Compute y min and max and y scale and set labels""" if self._min: self._box.ymin = min(self._min, self.zero) if self._max: self._box.ymax = max(self._max, self.zero) self._x_pos = [ x / self._len for x in range(self._len + 1) ] if self._len > 1 else [0, 1] # Center if only one value self._points(self._x_pos) self._x_pos = [(i + .5) / self._len for i in range(self._len)] def _plot(self): """Draw bars for series and secondary series""" for serie in self.series: self.bar(serie) for serie in self.secondary_series: self.bar(serie, True)
(config=None, **kwargs)
18,590
pygal.graph.public
__call__
Call api: chart(1, 2, 3, title='T')
def __call__(self, *args, **kwargs): """Call api: chart(1, 2, 3, title='T')""" self.raw_series.append((args, kwargs)) return self
(self, *args, **kwargs)
18,591
pygal.graph.base
__getattribute__
Get an attribute from the class or from the state if there is one
def __getattribute__(self, name): """Get an attribute from the class or from the state if there is one""" if name.startswith('__') or name == 'state' or getattr( self, 'state', None) is None or name not in self.state.__dict__: return super(BaseGraph, self).__getattribute__(name) return getattr(self.state, name)
(self, name)
18,592
pygal.graph.base
__init__
Config preparation and various initialization
def __init__(self, config=None, **kwargs): """Config preparation and various initialization""" if config: if isinstance(config, type): config = config() else: config = config.copy() else: config = Config() config(**kwargs) self.config = config self.state = None self.uuid = str(uuid4()) self.raw_series = [] self.xml_filters = []
(self, config=None, **kwargs)
18,593
pygal.graph.base
__setattr__
Set an attribute on the class or in the state if there is one
def __setattr__(self, name, value): """Set an attribute on the class or in the state if there is one""" if name.startswith('__') or getattr(self, 'state', None) is None: super(BaseGraph, self).__setattr__(name, value) else: setattr(self.state, name, value)
(self, name, value)
18,594
pygal.graph.graph
_axes
Draw axes
def _axes(self): """Draw axes""" self._y_axis() self._x_axis()
(self)
18,595
pygal.graph.bar
_bar
Internal bar drawing function
def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal bar drawing function""" width = (self.view.x(1) - self.view.x(0)) / self._len x, y = self.view((x, y)) series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin width /= self._order if self.horizontal: serie_index = self._order - serie.index - 1 else: serie_index = serie.index x += serie_index * width serie_margin = width * self._serie_margin x += serie_margin width -= 2 * serie_margin height = self.view.y(zero) - y r = serie.rounded_bars * 1 if serie.rounded_bars else 0 alter( self.svg.transposable_node( parent, 'rect', x=x, y=y, rx=r, ry=r, width=width, height=height, class_='rect reactive tooltip-trigger' ), serie.metadata.get(i) ) return x, y, width, height
(self, serie, parent, x, y, i, zero, secondary=False)
18,596
pygal.graph.bar
_compute
Compute y min and max and y scale and set labels
def _compute(self): """Compute y min and max and y scale and set labels""" if self._min: self._box.ymin = min(self._min, self.zero) if self._max: self._box.ymax = max(self._max, self.zero) self._x_pos = [ x / self._len for x in range(self._len + 1) ] if self._len > 1 else [0, 1] # Center if only one value self._points(self._x_pos) self._x_pos = [(i + .5) / self._len for i in range(self._len)]
(self)
18,597
pygal.graph.graph
_compute_margin
Compute graph margins from set texts
def _compute_margin(self): """Compute graph margins from set texts""" self._legend_at_left_width = 0 for series_group in (self.series, self.secondary_series): if self.show_legend and series_group: h, w = get_texts_box( map( lambda x: truncate(x, self.truncate_legend or 15), [ serie.title['title'] if isinstance(serie.title, dict) else serie.title or '' for serie in series_group ] ), self.style.legend_font_size ) if self.legend_at_bottom: h_max = max(h, self.legend_box_size) cols = ( self._order // self.legend_at_bottom_columns if self.legend_at_bottom_columns else ceil(sqrt(self._order)) or 1 ) self.margin_box.bottom += self.spacing + h_max * round( cols - 1 ) * 1.5 + h_max else: if series_group is self.series: legend_width = self.spacing + w + self.legend_box_size self.margin_box.left += legend_width self._legend_at_left_width += legend_width else: self.margin_box.right += ( self.spacing + w + self.legend_box_size ) self._x_labels_height = 0 if (self._x_labels or self._x_2nd_labels) and self.show_x_labels: for xlabels in (self._x_labels, self._x_2nd_labels): if xlabels: h, w = get_texts_box( map( lambda x: truncate(x, self.truncate_label or 25), cut(xlabels) ), self.style.label_font_size ) self._x_labels_height = self.spacing + max( w * abs(sin(rad(self.x_label_rotation))), h ) if xlabels is self._x_labels: self.margin_box.bottom += self._x_labels_height else: self.margin_box.top += self._x_labels_height if self.x_label_rotation: if self.x_label_rotation % 180 < 90: self.margin_box.right = max( w * abs(cos(rad(self.x_label_rotation))), self.margin_box.right ) else: self.margin_box.left = max( w * abs(cos(rad(self.x_label_rotation))), self.margin_box.left ) if self.show_y_labels: for ylabels in (self._y_labels, self._y_2nd_labels): if ylabels: h, w = get_texts_box( cut(ylabels), self.style.label_font_size ) if ylabels is self._y_labels: self.margin_box.left += self.spacing + max( w * abs(cos(rad(self.y_label_rotation))), h ) else: self.margin_box.right += self.spacing + max( w * abs(cos(rad(self.y_label_rotation))), h ) self._title = split_title( self.title, self.width, self.style.title_font_size ) if self.title: h, _ = get_text_box(self._title[0], self.style.title_font_size) self.margin_box.top += len(self._title) * (self.spacing + h) self._x_title = split_title( self.x_title, self.width - self.margin_box.x, self.style.title_font_size ) self._x_title_height = 0 if self._x_title: h, _ = get_text_box(self._x_title[0], self.style.title_font_size) height = len(self._x_title) * (self.spacing + h) self.margin_box.bottom += height self._x_title_height = height + self.spacing self._y_title = split_title( self.y_title, self.height - self.margin_box.y, self.style.title_font_size ) self._y_title_height = 0 if self._y_title: h, _ = get_text_box(self._y_title[0], self.style.title_font_size) height = len(self._y_title) * (self.spacing + h) self.margin_box.left += height self._y_title_height = height + self.spacing # Inner margin if self.print_values_position == 'top': gh = self.height - self.margin_box.y alpha = 1.1 * (self.style.value_font_size / gh) * self._box.height if self._max and self._max > 0: self._box.ymax += alpha if self._min and self._min < 0: self._box.ymin -= alpha
(self)
18,598
pygal.graph.graph
_compute_secondary
Compute secondary axis min max and label positions
def _compute_secondary(self): """Compute secondary axis min max and label positions""" # secondary y axis support if self.secondary_series and self._y_labels: y_pos = list(zip(*self._y_labels))[1] if self.include_x_axis: ymin = min(self._secondary_min, 0) ymax = max(self._secondary_max, 0) else: ymin = self._secondary_min ymax = self._secondary_max steps = len(y_pos) left_range = abs(y_pos[-1] - y_pos[0]) right_range = abs(ymax - ymin) or 1 scale = right_range / ((steps - 1) or 1) self._y_2nd_labels = [(self._y_format(ymin + i * scale), pos) for i, pos in enumerate(y_pos)] self._scale = left_range / right_range self._scale_diff = y_pos[0] self._scale_min_2nd = ymin
(self)
18,599
pygal.graph.graph
_compute_x_labels
null
def _compute_x_labels(self): self._x_labels = self.x_labels and list( zip( map(self._x_label_format_if_value, self.x_labels), self._x_pos ) )
(self)
18,600
pygal.graph.graph
_compute_x_labels_major
null
def _compute_x_labels_major(self): if self.x_labels_major_every: self._x_labels_major = [ self._x_labels[i][0] for i in range(0, len(self._x_labels), self.x_labels_major_every) ] elif self.x_labels_major_count: label_count = len(self._x_labels) major_count = self.x_labels_major_count if (major_count >= label_count): self._x_labels_major = [label[0] for label in self._x_labels] else: self._x_labels_major = [ self._x_labels[int( i * (label_count - 1) / (major_count - 1) )][0] for i in range(major_count) ] else: self._x_labels_major = self.x_labels_major and list( map(self._x_label_format_if_value, self.x_labels_major) ) or []
(self)
18,601
pygal.graph.graph
_compute_y_labels
null
def _compute_y_labels(self): y_pos = compute_scale( self._box.ymin, self._box.ymax, self.logarithmic, self.order_min, self.min_scale, self.max_scale ) if self.y_labels: self._y_labels = [] for i, y_label in enumerate(self.y_labels): if isinstance(y_label, dict): pos = self._adapt(y_label.get('value')) title = y_label.get('label', self._y_format(pos)) elif is_str(y_label): pos = self._adapt(y_pos[i % len(y_pos)]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self._box.ymin = min(self._box.ymin, min(cut(self._y_labels, 1))) self._box.ymax = max(self._box.ymax, max(cut(self._y_labels, 1))) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos))
(self)
18,602
pygal.graph.graph
_compute_y_labels_major
null
def _compute_y_labels_major(self): if self.y_labels_major_every: self._y_labels_major = [ self._y_labels[i][1] for i in range(0, len(self._y_labels), self.y_labels_major_every) ] elif self.y_labels_major_count: label_count = len(self._y_labels) major_count = self.y_labels_major_count if (major_count >= label_count): self._y_labels_major = [label[1] for label in self._y_labels] else: self._y_labels_major = [ self._y_labels[int( i * (label_count - 1) / (major_count - 1) )][1] for i in range(major_count) ] elif self.y_labels_major: self._y_labels_major = list(map(self._adapt, self.y_labels_major)) elif self._y_labels: self._y_labels_major = majorize(cut(self._y_labels, 1)) else: self._y_labels_major = []
(self)
18,603
pygal.graph.graph
_confidence_interval
null
def _confidence_interval(self, node, x, y, value, metadata): if not metadata or 'ci' not in metadata: return ci = metadata['ci'] ci['point_estimate'] = value low, high = getattr( stats, 'confidence_interval_%s' % ci.get('type', 'manual') )(**ci) self.svg.confidence_interval( node, x, # Respect some charts y modifications (pyramid, stackbar) y + (self.view.y(low) - self.view.y(value)), y + (self.view.y(high) - self.view.y(value)) )
(self, node, x, y, value, metadata)
18,604
pygal.graph.graph
_decorate
Draw all decorations
def _decorate(self): """Draw all decorations""" self._set_view() self._make_graph() self._axes() self._legend() self._make_title() self._make_x_title() self._make_y_title()
(self)
18,605
pygal.graph.graph
_draw
Draw all the things
def _draw(self): """Draw all the things""" self._compute() self._compute_x_labels() self._compute_x_labels_major() self._compute_y_labels() self._compute_y_labels_major() self._compute_secondary() self._post_compute() self._compute_margin() self._decorate() if self.series and self._has_data() and self._values: self._plot() else: self.svg.draw_no_data()
(self)
18,606
pygal.graph.graph
_format
Format the nth value for the serie
def _format(self, serie, i): """Format the nth value for the serie""" value = serie.values[i] metadata = serie.metadata.get(i) kwargs = {'chart': self, 'serie': serie, 'index': i} formatter = ((metadata and metadata.get('formatter')) or serie.formatter or self.formatter or self._value_format) kwargs = filter_kwargs(formatter, kwargs) return formatter(value, **kwargs)
(self, serie, i)
18,607
pygal.graph.graph
_get_x_label
Convenience function to get the x_label of a value index
def _get_x_label(self, i): """Convenience function to get the x_label of a value index""" if not self.x_labels or not self._x_labels or len(self._x_labels) <= i: return return self._x_labels[i][0]
(self, i)
18,608
pygal.graph.graph
_has_data
Check if there is any data
def _has_data(self): """Check if there is any data""" return any([ len([ v for a in (s[0] if is_list_like(s) else [s]) for v in (a if is_list_like(a) else [a]) if v is not None ]) for s in self.raw_series ])
(self)
18,609
pygal.graph.graph
_interpolate
Make the interpolation
def _interpolate(self, xs, ys): """Make the interpolation""" x = [] y = [] for i in range(len(ys)): if ys[i] is not None: x.append(xs[i]) y.append(ys[i]) interpolate = INTERPOLATIONS[self.interpolate] return list( interpolate( x, y, self.interpolation_precision, **self.interpolation_parameters ) )
(self, xs, ys)
18,610
pygal.graph.graph
_legend
Make the legend box
def _legend(self): """Make the legend box""" if not self.show_legend: return truncation = self.truncate_legend if self.legend_at_bottom: x = self.margin_box.left + self.spacing y = ( self.margin_box.top + self.view.height + self._x_title_height + self._x_labels_height + self.spacing ) cols = self.legend_at_bottom_columns or ceil(sqrt(self._order) ) or 1 if not truncation: available_space = self.view.width / cols - ( self.legend_box_size + 5 ) truncation = reverse_text_len( available_space, self.style.legend_font_size ) else: x = self.spacing y = self.margin_box.top + self.spacing cols = 1 if not truncation: truncation = 15 legends = self.svg.node( self.nodes['graph'], class_='legends', transform='translate(%d, %d)' % (x, y) ) h = max(self.legend_box_size, self.style.legend_font_size) x_step = self.view.width / cols if self.legend_at_bottom: secondary_legends = legends # svg node is the same else: # draw secondary axis on right x = self.margin_box.left + self.view.width + self.spacing if self._y_2nd_labels: h, w = get_texts_box( cut(self._y_2nd_labels), self.style.label_font_size ) x += self.spacing + max( w * abs(cos(rad(self.y_label_rotation))), h ) y = self.margin_box.top + self.spacing secondary_legends = self.svg.node( self.nodes['graph'], class_='legends', transform='translate(%d, %d)' % (x, y) ) serie_number = -1 i = 0 for titles, is_secondary in ((self._legends, False), (self._secondary_legends, True)): if not self.legend_at_bottom and is_secondary: i = 0 for title in titles: serie_number += 1 if title is None: continue col = i % cols row = i // cols legend = self.svg.node( secondary_legends if is_secondary else legends, class_='legend reactive activate-serie', id="activate-serie-%d" % serie_number ) self.svg.node( legend, 'rect', x=col * x_step, y=1.5 * row * h + ( self.style.legend_font_size - self.legend_box_size if self.style.legend_font_size > self.legend_box_size else 0 ) / 2, width=self.legend_box_size, height=self.legend_box_size, class_="color-%d reactive" % serie_number ) if isinstance(title, dict): node = decorate(self.svg, legend, title) title = title['title'] else: node = legend truncated = truncate(title, truncation) self.svg.node( node, 'text', x=col * x_step + self.legend_box_size + 5, y=1.5 * row * h + .5 * h + .3 * self.style.legend_font_size ).text = truncated if truncated != title: self.svg.node(legend, 'title').text = title i += 1
(self)
18,611
pygal.graph.graph
_make_graph
Init common graph svg structure
def _make_graph(self): """Init common graph svg structure""" self.nodes['graph'] = self.svg.node( class_='graph %s-graph %s' % ( self.__class__.__name__.lower(), 'horizontal' if self.horizontal else 'vertical' ) ) self.svg.node( self.nodes['graph'], 'rect', class_='background', x=0, y=0, width=self.width, height=self.height ) self.nodes['plot'] = self.svg.node( self.nodes['graph'], class_="plot", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.svg.node( self.nodes['plot'], 'rect', class_='background', x=0, y=0, width=self.view.width, height=self.view.height ) self.nodes['title'] = self.svg.node( self.nodes['graph'], class_="titles" ) self.nodes['overlay'] = self.svg.node( self.nodes['graph'], class_="plot overlay", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.nodes['text_overlay'] = self.svg.node( self.nodes['graph'], class_="plot text-overlay", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.nodes['tooltip_overlay'] = self.svg.node( self.nodes['graph'], class_="plot tooltip-overlay", transform="translate(%d, %d)" % (self.margin_box.left, self.margin_box.top) ) self.nodes['tooltip'] = self.svg.node( self.nodes['tooltip_overlay'], transform='translate(0 0)', style="opacity: 0", **{'class': 'tooltip'} ) self.svg.node( self.nodes['tooltip'], 'rect', rx=self.tooltip_border_radius, ry=self.tooltip_border_radius, width=0, height=0, **{'class': 'tooltip-box'} ) self.svg.node(self.nodes['tooltip'], 'g', class_='text')
(self)
18,612
pygal.graph.graph
_make_title
Make the title
def _make_title(self): """Make the title""" if self._title: for i, title_line in enumerate(self._title, 1): self.svg.node( self.nodes['title'], 'text', class_='title plot_title', x=self.width / 2, y=i * (self.style.title_font_size + self.spacing) ).text = title_line
(self)
18,613
pygal.graph.graph
_make_x_title
Make the X-Axis title
def _make_x_title(self): """Make the X-Axis title""" y = (self.height - self.margin_box.bottom + self._x_labels_height) if self._x_title: for i, title_line in enumerate(self._x_title, 1): text = self.svg.node( self.nodes['title'], 'text', class_='title', x=self.margin_box.left + self.view.width / 2, y=y + i * (self.style.title_font_size + self.spacing) ) text.text = title_line
(self)
18,614
pygal.graph.graph
_make_y_title
Make the Y-Axis title
def _make_y_title(self): """Make the Y-Axis title""" if self._y_title: yc = self.margin_box.top + self.view.height / 2 for i, title_line in enumerate(self._y_title, 1): text = self.svg.node( self.nodes['title'], 'text', class_='title', x=self._legend_at_left_width, y=i * (self.style.title_font_size + self.spacing) + yc ) text.attrib['transform'] = "rotate(%d %f %f)" % ( -90, self._legend_at_left_width, yc ) text.text = title_line
(self)
18,615
pygal.graph.bar
_plot
Draw bars for series and secondary series
def _plot(self): """Draw bars for series and secondary series""" for serie in self.series: self.bar(serie) for serie in self.secondary_series: self.bar(serie, True)
(self)
18,616
pygal.graph.graph
_points
Convert given data values into drawable points (x, y) and interpolated points if interpolate option is specified
def _points(self, x_pos): """ Convert given data values into drawable points (x, y) and interpolated points if interpolate option is specified """ for serie in self.all_series: serie.points = [(x_pos[i], v) for i, v in enumerate(serie.values)] if serie.points and self.interpolate: serie.interpolated = self._interpolate(x_pos, serie.values) else: serie.interpolated = []
(self, x_pos)
18,617
pygal.graph.graph
_post_compute
Hook called after compute and before margin computations and plot
def _post_compute(self): """Hook called after compute and before margin computations and plot""" pass
(self)
18,618
pygal.graph.base
_repr_png_
Display png in IPython notebook
def _repr_png_(self): """Display png in IPython notebook""" return self.render_to_png()
(self)
18,619
pygal.graph.base
_repr_svg_
Display svg in IPython notebook
def _repr_svg_(self): """Display svg in IPython notebook""" return self.render(disable_xml_declaration=True)
(self)
18,620
pygal.graph.graph
_rescale
Scale for secondary
def _rescale(self, points): """Scale for secondary""" return [( x, self._scale_diff + (y - self._scale_min_2nd) * self._scale if y is not None else None ) for x, y in points]
(self, points)
18,621
pygal.graph.graph
_serie_format
Format an independent value for the serie
def _serie_format(self, serie, value): """Format an independent value for the serie""" kwargs = {'chart': self, 'serie': serie, 'index': None} formatter = (serie.formatter or self.formatter or self._value_format) kwargs = filter_kwargs(formatter, kwargs) return formatter(value, **kwargs)
(self, serie, value)
18,622
pygal.graph.graph
_set_view
Assign a view to current graph
def _set_view(self): """Assign a view to current graph""" if self.logarithmic: if self._dual: view_class = XYLogView else: view_class = LogView else: view_class = ReverseView if self.inverse_y_axis else View self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box )
(self)
18,623
pygal.graph.graph
_static_value
Write the print value
def _static_value( self, serie_node, value, x, y, metadata, align_text='left', classes=None ): """Write the print value""" label = metadata and metadata.get('label') classes = classes and [classes] or [] if self.print_labels and label: label_cls = classes + ['label'] if self.print_values: y -= self.style.value_font_size / 2 self.svg.node( serie_node['text_overlay'], 'text', class_=' '.join(label_cls), x=x, y=y + self.style.value_font_size / 3 ).text = label y += self.style.value_font_size if self.print_values or self.dynamic_print_values: val_cls = classes + ['value'] if self.dynamic_print_values: val_cls.append('showable') self.svg.node( serie_node['text_overlay'], 'text', class_=' '.join(val_cls), x=x, y=y + self.style.value_font_size / 3, attrib={ 'text-anchor': align_text } ).text = value if self.print_zeroes or value != '0' else ''
(self, serie_node, value, x, y, metadata, align_text='left', classes=None)
18,624
pygal.graph.bar
_tooltip_and_print_values
null
def _tooltip_and_print_values( self, serie_node, serie, parent, i, val, metadata, x, y, width, height ): transpose = swap if self.horizontal else ident x_center, y_center = transpose((x + width / 2, y + height / 2)) x_top, y_top = transpose((x + width, y + height)) x_bottom, y_bottom = transpose((x, y)) if self._dual: v = serie.values[i][0] else: v = serie.values[i] sign = -1 if v < self.zero else 1 self._tooltip_data( parent, val, x_center, y_center, "centered", self._get_x_label(i) ) if self.print_values_position == 'top': if self.horizontal: x = x_bottom + sign * self.style.value_font_size / 2 y = y_center else: x = x_center y = y_bottom - sign * self.style.value_font_size / 2 elif self.print_values_position == 'bottom': if self.horizontal: x = x_top + sign * self.style.value_font_size / 2 y = y_center else: x = x_center y = y_top - sign * self.style.value_font_size / 2 else: x = x_center y = y_center self._static_value(serie_node, val, x, y, metadata, "middle")
(self, serie_node, serie, parent, i, val, metadata, x, y, width, height)
18,625
pygal.graph.graph
_tooltip_data
Insert in desc tags informations for the javascript tooltip
def _tooltip_data(self, node, value, x, y, classes=None, xlabel=None): """Insert in desc tags informations for the javascript tooltip""" self.svg.node(node, 'desc', class_="value").text = value if classes is None: classes = [] if x > self.view.width / 2: classes.append('left') if y > self.view.height / 2: classes.append('top') classes = ' '.join(classes) self.svg.node(node, 'desc', class_="x " + classes).text = to_str(x) self.svg.node(node, 'desc', class_="y " + classes).text = to_str(y) if xlabel: self.svg.node(node, 'desc', class_="x_label").text = to_str(xlabel)
(self, node, value, x, y, classes=None, xlabel=None)
18,626
pygal.graph.graph
_value_format
Format value for value display. (Varies in type between chart types)
def _value_format(self, value): """ Format value for value display. (Varies in type between chart types) """ return self._y_format(value)
(self, value)
18,627
pygal.graph.graph
_x_axis
Make the x axis: labels and guides
def _x_axis(self): """Make the x axis: labels and guides""" if not self._x_labels or not self.show_x_labels: return axis = self.svg.node( self.nodes['plot'], class_="axis x%s" % (' always_show' if self.show_x_guides else '') ) truncation = self.truncate_label if not truncation: if self.x_label_rotation or len(self._x_labels) <= 1: truncation = 25 else: first_label_position = self.view.x(self._x_labels[0][1]) or 0 last_label_position = self.view.x(self._x_labels[-1][1]) or 0 available_space = (last_label_position - first_label_position ) / len(self._x_labels) - 1 truncation = reverse_text_len( available_space, self.style.label_font_size ) truncation = max(truncation, 1) lastlabel = self._x_labels[-1][0] if 0 not in [label[1] for label in self._x_labels]: self.svg.node( axis, 'path', d='M%f %f v%f' % (0, 0, self.view.height), class_='line' ) lastlabel = None for label, position in self._x_labels: if self.horizontal: major = position in self._x_labels_major else: major = label in self._x_labels_major if not (self.show_minor_x_labels or major): continue guides = self.svg.node(axis, class_='guides') x = self.view.x(position) if x is None: continue y = self.view.height + 5 last_guide = (self._y_2nd_labels and label == lastlabel) self.svg.node( guides, 'path', d='M%f %f v%f' % (x or 0, 0, self.view.height), class_='%s%s%sline' % ( 'axis ' if label == "0" else '', 'major ' if major else '', 'guide ' if position != 0 and not last_guide else '' ) ) y += .5 * self.style.label_font_size + 5 text = self.svg.node( guides, 'text', x=x, y=y, class_='major' if major else '' ) text.text = truncate(label, truncation) if text.text != label: self.svg.node(guides, 'title').text = label elif self._dual: self.svg.node( guides, 'title', ).text = self._x_format(position) if self.x_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( self.x_label_rotation, x, y ) if self.x_label_rotation >= 180: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards']) if self._y_2nd_labels and 0 not in [label[1] for label in self._x_labels]: self.svg.node( axis, 'path', d='M%f %f v%f' % (self.view.width, 0, self.view.height), class_='line' ) if self._x_2nd_labels: secondary_ax = self.svg.node( self.nodes['plot'], class_="axis x x2%s" % (' always_show' if self.show_x_guides else '') ) for label, position in self._x_2nd_labels: major = label in self._x_labels_major if not (self.show_minor_x_labels or major): continue # it is needed, to have the same structure as primary axis guides = self.svg.node(secondary_ax, class_='guides') x = self.view.x(position) y = -5 text = self.svg.node( guides, 'text', x=x, y=y, class_='major' if major else '' ) text.text = label if self.x_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( -self.x_label_rotation, x, y ) if self.x_label_rotation >= 180: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards'])
(self)
18,628
pygal.graph.graph
_x_label_format_if_value
null
def _x_label_format_if_value(self, label): if not is_str(label): return self._x_format(label) return label
(self, label)
18,629
pygal.graph.graph
_y_axis
Make the y axis: labels and guides
def _y_axis(self): """Make the y axis: labels and guides""" if not self._y_labels or not self.show_y_labels: return axis = self.svg.node( self.nodes['plot'], class_="axis y%s" % (' always_show' if self.show_y_guides else '') ) if (0 not in [label[1] for label in self._y_labels] and self.show_y_guides): self.svg.node( axis, 'path', d='M%f %f h%f' % ( 0, 0 if self.inverse_y_axis else self.view.height, self.view.width ), class_='line' ) for label, position in self._y_labels: if self.horizontal: major = label in self._y_labels_major else: major = position in self._y_labels_major if not (self.show_minor_y_labels or major): continue guides = self.svg.node( axis, class_='%sguides' % ('logarithmic ' if self.logarithmic else '') ) x = -5 y = self.view.y(position) if not y: continue if self.show_y_guides: self.svg.node( guides, 'path', d='M%f %f h%f' % (0, y, self.view.width), class_='%s%s%sline' % ( 'axis ' if label == "0" else '', 'major ' if major else '', 'guide ' if position != 0 else '' ) ) text = self.svg.node( guides, 'text', x=x, y=y + .35 * self.style.label_font_size, class_='major' if major else '' ) text.text = label if self.y_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( self.y_label_rotation, x, y ) if 90 < self.y_label_rotation < 270: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards']) self.svg.node( guides, 'title', ).text = self._y_format(position) if self._y_2nd_labels: secondary_ax = self.svg.node(self.nodes['plot'], class_="axis y2") for label, position in self._y_2nd_labels: major = position in self._y_labels_major if not (self.show_minor_y_labels or major): continue # it is needed, to have the same structure as primary axis guides = self.svg.node(secondary_ax, class_='guides') x = self.view.width + 5 y = self.view.y(position) text = self.svg.node( guides, 'text', x=x, y=y + .35 * self.style.label_font_size, class_='major' if major else '' ) text.text = label if self.y_label_rotation: text.attrib['transform'] = "rotate(%d %f %f)" % ( self.y_label_rotation, x, y ) if 90 < self.y_label_rotation < 270: text.attrib['class'] = ' '.join(( text.attrib['class'] and text.attrib['class'].split(' ') or [] ) + ['backwards'])
(self)
18,630
pygal.graph.public
add
Add a serie to this graph, compat api
def add(self, title, values, **kwargs): """Add a serie to this graph, compat api""" if not is_list_like(values) and not isinstance(values, dict): values = [values] kwargs['title'] = title self.raw_series.append((values, kwargs)) return self
(self, title, values, **kwargs)
18,631
pygal.graph.graph
add_squares
null
def add_squares(self, squares): x_lines = squares[0] - 1 y_lines = squares[1] - 1 _current_x = 0 _current_y = 0 for line in range(x_lines): _current_x += (self.width - self.margin_box.x) / squares[0] self.svg.node( self.nodes['plot'], 'path', class_='bg-lines', d='M%s %s L%s %s' % (_current_x, 0, _current_x, self.height - self.margin_box.y) ) for line in range(y_lines): _current_y += (self.height - self.margin_box.y) / squares[1] self.svg.node( self.nodes['plot'], 'path', class_='bg-lines', d='M%s %s L%s %s' % (0, _current_y, self.width - self.margin_box.x, _current_y) ) return ((self.width - self.margin_box.x) / squares[0], (self.height - self.margin_box.y) / squares[1])
(self, squares)
18,632
pygal.graph.public
add_xml_filter
Add an xml filter for in tree post processing
def add_xml_filter(self, callback): """Add an xml filter for in tree post processing""" self.xml_filters.append(callback) return self
(self, callback)
18,633
pygal.graph.bar
bar
Draw a bar graph for a serie
def bar(self, serie, rescale=False): """Draw a bar graph for a serie""" serie_node = self.svg.serie(serie) bars = self.svg.node(serie_node['plot'], class_="bars") if rescale and self.secondary_series: points = self._rescale(serie.points) else: points = serie.points for i, (x, y) in enumerate(points): if None in (x, y) or (self.logarithmic and y <= 0): continue metadata = serie.metadata.get(i) val = self._format(serie, i) bar = decorate( self.svg, self.svg.node(bars, class_='bar'), metadata ) x_, y_, width, height = self._bar( serie, bar, x, y, i, self.zero, secondary=rescale ) self._confidence_interval( serie_node['overlay'], x_ + width / 2, y_, serie.values[i], metadata ) self._tooltip_and_print_values( serie_node, serie, bar, i, val, metadata, x_, y_, width, height )
(self, serie, rescale=False)
18,634
pygal.graph.base
prepare_values
Prepare the values to start with sane values
def prepare_values(self, raw, offset=0): """Prepare the values to start with sane values""" from pygal import Histogram from pygal.graph.map import BaseMap if self.zero == 0 and isinstance(self, BaseMap): self.zero = 1 if self.x_label_rotation: self.x_label_rotation %= 360 if self.y_label_rotation: self.y_label_rotation %= 360 for key in ('x_labels', 'y_labels'): if getattr(self, key): setattr(self, key, list(getattr(self, key))) if not raw: return adapters = list(self._adapters) or [lambda x: x] if self.logarithmic: for fun in not_zero, positive: if fun in adapters: adapters.remove(fun) adapters = adapters + [positive, not_zero] adapters = adapters + [decimal_to_float] self._adapt = reduce(compose, adapters) if not self.strict else ident self._x_adapt = reduce( compose, self._x_adapters ) if not self.strict and getattr(self, '_x_adapters', None) else ident series = [] raw = [( list(raw_values) if not isinstance(raw_values, dict) else raw_values, serie_config_kwargs ) for raw_values, serie_config_kwargs in raw] width = max([len(values) for values, _ in raw] + [len(self.x_labels or [])]) for raw_values, serie_config_kwargs in raw: metadata = {} values = [] if isinstance(raw_values, dict): if isinstance(self, BaseMap): raw_values = list(raw_values.items()) else: value_list = [None] * width for k, v in raw_values.items(): if k in (self.x_labels or []): value_list[self.x_labels.index(k)] = v raw_values = value_list for index, raw_value in enumerate(raw_values + ( (width - len(raw_values)) * [None] # aligning values if len(raw_values) < width else [])): if isinstance(raw_value, dict): raw_value = dict(raw_value) value = raw_value.pop('value', None) metadata[index] = raw_value else: value = raw_value # Fix this by doing this in charts class methods if isinstance(self, Histogram): if value is None: value = (None, None, None) elif not is_list_like(value): value = (value, self.zero, self.zero) elif len(value) == 2: value = (1, value[0], value[1]) value = list(map(self._adapt, value)) elif self._dual: if value is None: value = (None, None) elif not is_list_like(value): value = (value, self.zero) if self._x_adapt: value = ( self._x_adapt(value[0]), self._adapt(value[1]) ) if isinstance(self, BaseMap): value = (self._adapt(value[0]), value[1]) else: value = list(map(self._adapt, value)) else: value = self._adapt(value) values.append(value) serie_config = SerieConfig() serie_config( **dict((k, v) for k, v in self.state.__dict__.items() if k in dir(serie_config)) ) serie_config(**serie_config_kwargs) series.append( Serie(offset + len(series), values, serie_config, metadata) ) return series
(self, raw, offset=0)
18,635
pygal.graph.public
render
Render the graph, and return the svg string
def render(self, is_unicode=False, **kwargs): """Render the graph, and return the svg string""" self.setup(**kwargs) svg = self.svg.render( is_unicode=is_unicode, pretty_print=self.pretty_print ) self.teardown() return svg
(self, is_unicode=False, **kwargs)
18,636
pygal.graph.public
render_data_uri
Output a base 64 encoded data uri
def render_data_uri(self, **kwargs): """Output a base 64 encoded data uri""" # Force protocol as data uri have none kwargs.setdefault('force_uri_protocol', 'https') return "data:image/svg+xml;charset=utf-8;base64,%s" % ( base64.b64encode(self.render(**kwargs) ).decode('utf-8').replace('\n', '') )
(self, **kwargs)
18,637
pygal.graph.public
render_django_response
Render the graph, and return a Django response
def render_django_response(self, **kwargs): """Render the graph, and return a Django response""" from django.http import HttpResponse return HttpResponse( self.render(**kwargs), content_type='image/svg+xml' )
(self, **kwargs)
18,638
pygal.graph.public
render_in_browser
Render the graph, open it in your browser with black magic
def render_in_browser(self, **kwargs): """Render the graph, open it in your browser with black magic""" try: from lxml.html import open_in_browser except ImportError: raise ImportError('You must install lxml to use render in browser') kwargs.setdefault('force_uri_protocol', 'https') open_in_browser(self.render_tree(**kwargs), encoding='utf-8')
(self, **kwargs)
18,639
pygal.graph.public
render_pyquery
Render the graph, and return a pyquery wrapped tree
def render_pyquery(self, **kwargs): """Render the graph, and return a pyquery wrapped tree""" from pyquery import PyQuery as pq return pq(self.render(**kwargs), parser='html')
(self, **kwargs)
18,640
pygal.graph.public
render_response
Render the graph, and return a Flask response
def render_response(self, **kwargs): """Render the graph, and return a Flask response""" from flask import Response return Response(self.render(**kwargs), mimetype='image/svg+xml')
(self, **kwargs)
18,641
pygal.graph.public
render_sparkline
Render a sparkline
def render_sparkline(self, **kwargs): """Render a sparkline""" spark_options = dict( width=200, height=50, show_dots=False, show_legend=False, show_x_labels=False, show_y_labels=False, spacing=0, margin=5, min_scale=1, max_scale=2, explicit_size=True, no_data_text='', js=(), classes=(_ellipsis, 'pygal-sparkline') ) spark_options.update(kwargs) return self.render(**spark_options)
(self, **kwargs)
18,642
pygal.graph.public
render_sparktext
Make a mini text sparkline from chart
def render_sparktext(self, relative_to=None): """Make a mini text sparkline from chart""" bars = u('▁▂▃▄▅▆▇█') if len(self.raw_series) == 0: return u('') values = list(self.raw_series[0][0]) if len(values) == 0: return u('') chart = u('') values = list(map(lambda x: max(x, 0), values)) vmax = max(values) if relative_to is None: relative_to = min(values) if (vmax - relative_to) == 0: chart = bars[0] * len(values) return chart divisions = len(bars) - 1 for value in values: chart += bars[int( divisions * (value - relative_to) / (vmax - relative_to) )] return chart
(self, relative_to=None)
18,643
pygal.graph.public
render_table
Render the data as a html table
def render_table(self, **kwargs): """Render the data as a html table""" # Import here to avoid lxml import try: from pygal.table import Table except ImportError: raise ImportError('You must install lxml to use render table') return Table(self).render(**kwargs)
(self, **kwargs)
18,644
pygal.graph.public
render_to_file
Render the graph, and write it to filename
def render_to_file(self, filename, **kwargs): """Render the graph, and write it to filename""" with io.open(filename, 'w', encoding='utf-8') as f: f.write(self.render(is_unicode=True, **kwargs))
(self, filename, **kwargs)
18,645
pygal.graph.public
render_to_png
Render the graph, convert it to png and write it to filename
def render_to_png(self, filename=None, dpi=72, **kwargs): """Render the graph, convert it to png and write it to filename""" import cairosvg return cairosvg.svg2png( bytestring=self.render(**kwargs), write_to=filename, dpi=dpi )
(self, filename=None, dpi=72, **kwargs)
18,646
pygal.graph.public
render_tree
Render the graph, and return (l)xml etree
def render_tree(self, **kwargs): """Render the graph, and return (l)xml etree""" self.setup(**kwargs) svg = self.svg.root for f in self.xml_filters: svg = f(svg) self.teardown() return svg
(self, **kwargs)
18,647
pygal.graph.base
setup
Set up the transient state prior rendering
def setup(self, **kwargs): """Set up the transient state prior rendering""" # Keep labels in case of map if getattr(self, 'x_labels', None) is not None: self.x_labels = list(self.x_labels) if getattr(self, 'y_labels', None) is not None: self.y_labels = list(self.y_labels) self.state = State(self, **kwargs) if isinstance(self.style, type): self.style = self.style() self.series = self.prepare_values([ rs for rs in self.raw_series if not rs[1].get('secondary') ]) or [] self.secondary_series = self.prepare_values([ rs for rs in self.raw_series if rs[1].get('secondary') ], len(self.series)) or [] self.horizontal = getattr(self, 'horizontal', False) self.svg = Svg(self) self._x_labels = None self._y_labels = None self._x_2nd_labels = None self._y_2nd_labels = None self.nodes = {} self.margin_box = Margin( self.margin_top or self.margin, self.margin_right or self.margin, self.margin_bottom or self.margin, self.margin_left or self.margin ) self._box = Box() self.view = None if self.logarithmic and self.zero == 0: # Explicit min to avoid interpolation dependency positive_values = list( filter( lambda x: x > 0, [ val[1] or 1 if self._dual else val for serie in self.series for val in serie.safe_values ] ) ) self.zero = min(positive_values or (1, )) or 1 if self._len < 3: self.interpolate = None self._draw() self.svg.pre_render()
(self, **kwargs)
18,648
pygal.graph.base
teardown
Remove the transient state after rendering
def teardown(self): """Remove the transient state after rendering""" if os.getenv('PYGAL_KEEP_STATE'): return del self.state self.state = None
(self)
18,649
pygal.graph.map
BaseMap
Base class for maps
class BaseMap(Graph): """Base class for maps""" _dual = True @cached_property def _values(self): """Getter for series values (flattened)""" return [ val[1] for serie in self.series for val in serie.values if val[1] is not None ] def enumerate_values(self, serie): """Hook to replace default enumeration on values""" return enumerate(serie.values) def adapt_code(self, area_code): """Hook to change the area code""" return area_code def _value_format(self, value): """ Format value for map value display. """ return '%s: %s' % ( self.area_names.get(self.adapt_code(value[0]), '?'), self._y_format(value[1]) ) def _plot(self): """Insert a map in the chart and apply data on it""" map = etree.fromstring(self.svg_map) map.set('width', str(self.view.width)) map.set('height', str(self.view.height)) for i, serie in enumerate(self.series): safe_vals = list( filter(lambda x: x is not None, cut(serie.values, 1)) ) if not safe_vals: continue min_ = min(safe_vals) max_ = max(safe_vals) for j, (area_code, value) in self.enumerate_values(serie): area_code = self.adapt_code(area_code) if value is None: continue if max_ == min_: ratio = 1 else: ratio = .3 + .7 * (value - min_) / (max_ - min_) areae = map.findall( ".//*[@class='%s%s %s map-element']" % (self.area_prefix, area_code, self.kind) ) if not areae: continue for area in areae: cls = area.get('class', '').split(' ') cls.append('color-%d' % i) cls.append('serie-%d' % i) cls.append('series') area.set('class', ' '.join(cls)) area.set('style', 'fill-opacity: %f' % ratio) metadata = serie.metadata.get(j) if metadata: node = decorate(self.svg, area, metadata) if node != area: area.remove(node) for g in map: if area not in g: continue index = list(g).index(area) g.remove(area) node.append(area) g.insert(index, node) for node in area: cls = node.get('class', '').split(' ') cls.append('reactive') cls.append('tooltip-trigger') cls.append('map-area') node.set('class', ' '.join(cls)) alter(node, metadata) val = self._format(serie, j) self._tooltip_data(area, val, 0, 0, 'auto') self.nodes['plot'].append(map) def _compute_x_labels(self): pass def _compute_y_labels(self): pass
(config=None, **kwargs)
18,655
pygal.graph.graph
_compute
Initial computations to draw the graph
def _compute(self): """Initial computations to draw the graph"""
(self)
18,658
pygal.graph.map
_compute_x_labels
null
def _compute_x_labels(self): pass
(self)
18,660
pygal.graph.map
_compute_y_labels
null
def _compute_y_labels(self): pass
(self)
18,674
pygal.graph.map
_plot
Insert a map in the chart and apply data on it
def _plot(self): """Insert a map in the chart and apply data on it""" map = etree.fromstring(self.svg_map) map.set('width', str(self.view.width)) map.set('height', str(self.view.height)) for i, serie in enumerate(self.series): safe_vals = list( filter(lambda x: x is not None, cut(serie.values, 1)) ) if not safe_vals: continue min_ = min(safe_vals) max_ = max(safe_vals) for j, (area_code, value) in self.enumerate_values(serie): area_code = self.adapt_code(area_code) if value is None: continue if max_ == min_: ratio = 1 else: ratio = .3 + .7 * (value - min_) / (max_ - min_) areae = map.findall( ".//*[@class='%s%s %s map-element']" % (self.area_prefix, area_code, self.kind) ) if not areae: continue for area in areae: cls = area.get('class', '').split(' ') cls.append('color-%d' % i) cls.append('serie-%d' % i) cls.append('series') area.set('class', ' '.join(cls)) area.set('style', 'fill-opacity: %f' % ratio) metadata = serie.metadata.get(j) if metadata: node = decorate(self.svg, area, metadata) if node != area: area.remove(node) for g in map: if area not in g: continue index = list(g).index(area) g.remove(area) node.append(area) g.insert(index, node) for node in area: cls = node.get('class', '').split(' ') cls.append('reactive') cls.append('tooltip-trigger') cls.append('map-area') node.set('class', ' '.join(cls)) alter(node, metadata) val = self._format(serie, j) self._tooltip_data(area, val, 0, 0, 'auto') self.nodes['plot'].append(map)
(self)
18,684
pygal.graph.map
_value_format
Format value for map value display.
def _value_format(self, value): """ Format value for map value display. """ return '%s: %s' % ( self.area_names.get(self.adapt_code(value[0]), '?'), self._y_format(value[1]) )
(self, value)
18,688
pygal.graph.map
adapt_code
Hook to change the area code
def adapt_code(self, area_code): """Hook to change the area code""" return area_code
(self, area_code)
18,692
pygal.graph.map
enumerate_values
Hook to replace default enumeration on values
def enumerate_values(self, serie): """Hook to replace default enumeration on values""" return enumerate(serie.values)
(self, serie)
18,708
pygal.graph.box
Box
Box plot For each series, shows the median value, the 25th and 75th percentiles, and the values within 1.5 times the interquartile range of the 25th and 75th percentiles. See http://en.wikipedia.org/wiki/Box_plot
class Box(Graph): """ Box plot For each series, shows the median value, the 25th and 75th percentiles, and the values within 1.5 times the interquartile range of the 25th and 75th percentiles. See http://en.wikipedia.org/wiki/Box_plot """ _series_margin = .06 def _value_format(self, value, serie): """ Format value for dual value display. """ if self.box_mode == "extremes": return ( 'Min: %s\nQ1 : %s\nQ2 : %s\nQ3 : %s\nMax: %s' % tuple(map(self._y_format, serie.points[1:6])) ) elif self.box_mode in ["tukey", "stdev", "pstdev"]: return ( 'Min: %s\nLower Whisker: %s\nQ1: %s\nQ2: %s\nQ3: %s\n' 'Upper Whisker: %s\nMax: %s' % tuple(map(self._y_format, serie.points)) ) elif self.box_mode == '1.5IQR': # 1.5IQR mode return 'Q1: %s\nQ2: %s\nQ3: %s' % tuple( map(self._y_format, serie.points[2:5]) ) else: return self._y_format(serie.points) def _compute(self): """ Compute parameters necessary for later steps within the rendering process """ for serie in self.series: serie.points, serie.outliers = \ self._box_points(serie.values, self.box_mode) self._x_pos = [(i + .5) / self._order for i in range(self._order)] if self._min: self._box.ymin = min(self._min, self.zero) if self._max: self._box.ymax = max(self._max, self.zero) def _plot(self): """Plot the series data""" for serie in self.series: self._boxf(serie) @property def _len(self): """Len is always 7 here""" return 7 def _boxf(self, serie): """For a specific series, draw the box plot.""" serie_node = self.svg.serie(serie) # Note: q0 and q4 do not literally mean the zero-th quartile # and the fourth quartile, but rather the distance from 1.5 times # the inter-quartile range to Q1 and Q3, respectively. boxes = self.svg.node(serie_node['plot'], class_="boxes") metadata = serie.metadata.get(0) box = decorate(self.svg, self.svg.node(boxes, class_='box'), metadata) val = self._format(serie, 0) x_center, y_center = self._draw_box( box, serie.points[1:6], serie.outliers, serie.index, metadata ) self._tooltip_data( box, val, x_center, y_center, "centered", self._get_x_label(serie.index) ) self._static_value(serie_node, val, x_center, y_center, metadata) def _draw_box(self, parent_node, quartiles, outliers, box_index, metadata): """ Return the center of a bounding box defined by a box plot. Draws a box plot on self.svg. """ width = (self.view.x(1) - self.view.x(0)) / self._order series_margin = width * self._series_margin left_edge = self.view.x(0) + width * box_index + series_margin width -= 2 * series_margin # draw lines for whiskers - bottom, median, and top for i, whisker in enumerate((quartiles[0], quartiles[2], quartiles[4])): whisker_width = width if i == 1 else width / 2 shift = (width - whisker_width) / 2 xs = left_edge + shift xe = left_edge + width - shift alter( self.svg.line( parent_node, coords=[(xs, self.view.y(whisker)), (xe, self.view.y(whisker))], class_='reactive tooltip-trigger', attrib={'stroke-width': 3} ), metadata ) # draw lines connecting whiskers to box (Q1 and Q3) alter( self.svg.line( parent_node, coords=[(left_edge + width / 2, self.view.y(quartiles[0])), (left_edge + width / 2, self.view.y(quartiles[1]))], class_='reactive tooltip-trigger', attrib={'stroke-width': 2} ), metadata ) alter( self.svg.line( parent_node, coords=[(left_edge + width / 2, self.view.y(quartiles[4])), (left_edge + width / 2, self.view.y(quartiles[3]))], class_='reactive tooltip-trigger', attrib={'stroke-width': 2} ), metadata ) # box, bounded by Q1 and Q3 alter( self.svg.node( parent_node, tag='rect', x=left_edge, y=self.view.y(quartiles[1]), height=self.view.y(quartiles[3]) - self.view.y(quartiles[1]), width=width, class_='subtle-fill reactive tooltip-trigger' ), metadata ) # draw outliers for o in outliers: alter( self.svg.node( parent_node, tag='circle', cx=left_edge + width / 2, cy=self.view.y(o), r=3, class_='subtle-fill reactive tooltip-trigger' ), metadata ) return ( left_edge + width / 2, self.view.y(sum(quartiles) / len(quartiles)) ) @staticmethod def _box_points(values, mode='extremes'): """ Default mode: (mode='extremes' or unset) Return a 7-tuple of 2x minimum, Q1, Median, Q3, and 2x maximum for a list of numeric values. 1.5IQR mode: (mode='1.5IQR') Return a 7-tuple of min, Q1 - 1.5 * IQR, Q1, Median, Q3, Q3 + 1.5 * IQR and max for a list of numeric values. Tukey mode: (mode='tukey') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q1 - IQR or x > q3 + IQR SD mode: (mode='stdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SD or x > q2 + SD SDp mode: (mode='pstdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SDp or x > q2 + SDp The iterator values may include None values. Uses quartile definition from Mendenhall, W. and Sincich, T. L. Statistics for Engineering and the Sciences, 4th ed. Prentice-Hall, 1995. """ def median(seq): n = len(seq) if n % 2 == 0: # seq has an even length return (seq[n // 2] + seq[n // 2 - 1]) / 2 else: # seq has an odd length return seq[n // 2] def mean(seq): return sum(seq) / len(seq) def stdev(seq): m = mean(seq) l = len(seq) v = sum((n - m)**2 for n in seq) / (l - 1) # variance return v**0.5 # sqrt def pstdev(seq): m = mean(seq) l = len(seq) v = sum((n - m)**2 for n in seq) / l # variance return v**0.5 # sqrt outliers = [] # sort the copy in case the originals must stay in original order s = sorted([x for x in values if x is not None]) n = len(s) if not n: return (0, 0, 0, 0, 0, 0, 0), [] elif n == 1: return (s[0], s[0], s[0], s[0], s[0], s[0], s[0]), [] else: q2 = median(s) # See 'Method 3' in http://en.wikipedia.org/wiki/Quartile if n % 2 == 0: # even q1 = median(s[:n // 2]) q3 = median(s[n // 2:]) else: # odd if n == 1: # special case q1 = s[0] q3 = s[0] elif n % 4 == 1: # n is of form 4n + 1 where n >= 1 m = (n - 1) // 4 q1 = 0.25 * s[m - 1] + 0.75 * s[m] q3 = 0.75 * s[3 * m] + 0.25 * s[3 * m + 1] else: # n is of form 4n + 3 where n >= 1 m = (n - 3) // 4 q1 = 0.75 * s[m] + 0.25 * s[m + 1] q3 = 0.25 * s[3 * m + 1] + 0.75 * s[3 * m + 2] iqr = q3 - q1 min_s = s[0] max_s = s[-1] if mode == 'extremes': q0 = min_s q4 = max_s elif mode == 'tukey': # the lowest datum still within 1.5 IQR of the lower quartile, # and the highest datum still within 1.5 IQR of the upper # quartile [Tukey box plot, Wikipedia ] b0 = bisect_left(s, q1 - 1.5 * iqr) b4 = bisect_right(s, q3 + 1.5 * iqr) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == 'stdev': # one standard deviation above and below the mean of the data sd = stdev(s) b0 = bisect_left(s, q2 - sd) b4 = bisect_right(s, q2 + sd) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == 'pstdev': # one population standard deviation above and below # the mean of the data sdp = pstdev(s) b0 = bisect_left(s, q2 - sdp) b4 = bisect_right(s, q2 + sdp) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == '1.5IQR': # 1.5IQR mode q0 = q1 - 1.5 * iqr q4 = q3 + 1.5 * iqr return (min_s, q0, q1, q2, q3, q4, max_s), outliers
(config=None, **kwargs)
18,714
pygal.graph.box
_box_points
Default mode: (mode='extremes' or unset) Return a 7-tuple of 2x minimum, Q1, Median, Q3, and 2x maximum for a list of numeric values. 1.5IQR mode: (mode='1.5IQR') Return a 7-tuple of min, Q1 - 1.5 * IQR, Q1, Median, Q3, Q3 + 1.5 * IQR and max for a list of numeric values. Tukey mode: (mode='tukey') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q1 - IQR or x > q3 + IQR SD mode: (mode='stdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SD or x > q2 + SD SDp mode: (mode='pstdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SDp or x > q2 + SDp The iterator values may include None values. Uses quartile definition from Mendenhall, W. and Sincich, T. L. Statistics for Engineering and the Sciences, 4th ed. Prentice-Hall, 1995.
@staticmethod def _box_points(values, mode='extremes'): """ Default mode: (mode='extremes' or unset) Return a 7-tuple of 2x minimum, Q1, Median, Q3, and 2x maximum for a list of numeric values. 1.5IQR mode: (mode='1.5IQR') Return a 7-tuple of min, Q1 - 1.5 * IQR, Q1, Median, Q3, Q3 + 1.5 * IQR and max for a list of numeric values. Tukey mode: (mode='tukey') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q1 - IQR or x > q3 + IQR SD mode: (mode='stdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SD or x > q2 + SD SDp mode: (mode='pstdev') Return a 7-tuple of min, q[0..4], max and a list of outliers Outliers are considered values x: x < q2 - SDp or x > q2 + SDp The iterator values may include None values. Uses quartile definition from Mendenhall, W. and Sincich, T. L. Statistics for Engineering and the Sciences, 4th ed. Prentice-Hall, 1995. """ def median(seq): n = len(seq) if n % 2 == 0: # seq has an even length return (seq[n // 2] + seq[n // 2 - 1]) / 2 else: # seq has an odd length return seq[n // 2] def mean(seq): return sum(seq) / len(seq) def stdev(seq): m = mean(seq) l = len(seq) v = sum((n - m)**2 for n in seq) / (l - 1) # variance return v**0.5 # sqrt def pstdev(seq): m = mean(seq) l = len(seq) v = sum((n - m)**2 for n in seq) / l # variance return v**0.5 # sqrt outliers = [] # sort the copy in case the originals must stay in original order s = sorted([x for x in values if x is not None]) n = len(s) if not n: return (0, 0, 0, 0, 0, 0, 0), [] elif n == 1: return (s[0], s[0], s[0], s[0], s[0], s[0], s[0]), [] else: q2 = median(s) # See 'Method 3' in http://en.wikipedia.org/wiki/Quartile if n % 2 == 0: # even q1 = median(s[:n // 2]) q3 = median(s[n // 2:]) else: # odd if n == 1: # special case q1 = s[0] q3 = s[0] elif n % 4 == 1: # n is of form 4n + 1 where n >= 1 m = (n - 1) // 4 q1 = 0.25 * s[m - 1] + 0.75 * s[m] q3 = 0.75 * s[3 * m] + 0.25 * s[3 * m + 1] else: # n is of form 4n + 3 where n >= 1 m = (n - 3) // 4 q1 = 0.75 * s[m] + 0.25 * s[m + 1] q3 = 0.25 * s[3 * m + 1] + 0.75 * s[3 * m + 2] iqr = q3 - q1 min_s = s[0] max_s = s[-1] if mode == 'extremes': q0 = min_s q4 = max_s elif mode == 'tukey': # the lowest datum still within 1.5 IQR of the lower quartile, # and the highest datum still within 1.5 IQR of the upper # quartile [Tukey box plot, Wikipedia ] b0 = bisect_left(s, q1 - 1.5 * iqr) b4 = bisect_right(s, q3 + 1.5 * iqr) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == 'stdev': # one standard deviation above and below the mean of the data sd = stdev(s) b0 = bisect_left(s, q2 - sd) b4 = bisect_right(s, q2 + sd) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == 'pstdev': # one population standard deviation above and below # the mean of the data sdp = pstdev(s) b0 = bisect_left(s, q2 - sdp) b4 = bisect_right(s, q2 + sdp) q0 = s[b0] q4 = s[b4 - 1] outliers = s[:b0] + s[b4:] elif mode == '1.5IQR': # 1.5IQR mode q0 = q1 - 1.5 * iqr q4 = q3 + 1.5 * iqr return (min_s, q0, q1, q2, q3, q4, max_s), outliers
(values, mode='extremes')
18,715
pygal.graph.box
_boxf
For a specific series, draw the box plot.
def _boxf(self, serie): """For a specific series, draw the box plot.""" serie_node = self.svg.serie(serie) # Note: q0 and q4 do not literally mean the zero-th quartile # and the fourth quartile, but rather the distance from 1.5 times # the inter-quartile range to Q1 and Q3, respectively. boxes = self.svg.node(serie_node['plot'], class_="boxes") metadata = serie.metadata.get(0) box = decorate(self.svg, self.svg.node(boxes, class_='box'), metadata) val = self._format(serie, 0) x_center, y_center = self._draw_box( box, serie.points[1:6], serie.outliers, serie.index, metadata ) self._tooltip_data( box, val, x_center, y_center, "centered", self._get_x_label(serie.index) ) self._static_value(serie_node, val, x_center, y_center, metadata)
(self, serie)
18,716
pygal.graph.box
_compute
Compute parameters necessary for later steps within the rendering process
def _compute(self): """ Compute parameters necessary for later steps within the rendering process """ for serie in self.series: serie.points, serie.outliers = \ self._box_points(serie.values, self.box_mode) self._x_pos = [(i + .5) / self._order for i in range(self._order)] if self._min: self._box.ymin = min(self._min, self.zero) if self._max: self._box.ymax = max(self._max, self.zero)
(self)
18,726
pygal.graph.box
_draw_box
Return the center of a bounding box defined by a box plot. Draws a box plot on self.svg.
def _draw_box(self, parent_node, quartiles, outliers, box_index, metadata): """ Return the center of a bounding box defined by a box plot. Draws a box plot on self.svg. """ width = (self.view.x(1) - self.view.x(0)) / self._order series_margin = width * self._series_margin left_edge = self.view.x(0) + width * box_index + series_margin width -= 2 * series_margin # draw lines for whiskers - bottom, median, and top for i, whisker in enumerate((quartiles[0], quartiles[2], quartiles[4])): whisker_width = width if i == 1 else width / 2 shift = (width - whisker_width) / 2 xs = left_edge + shift xe = left_edge + width - shift alter( self.svg.line( parent_node, coords=[(xs, self.view.y(whisker)), (xe, self.view.y(whisker))], class_='reactive tooltip-trigger', attrib={'stroke-width': 3} ), metadata ) # draw lines connecting whiskers to box (Q1 and Q3) alter( self.svg.line( parent_node, coords=[(left_edge + width / 2, self.view.y(quartiles[0])), (left_edge + width / 2, self.view.y(quartiles[1]))], class_='reactive tooltip-trigger', attrib={'stroke-width': 2} ), metadata ) alter( self.svg.line( parent_node, coords=[(left_edge + width / 2, self.view.y(quartiles[4])), (left_edge + width / 2, self.view.y(quartiles[3]))], class_='reactive tooltip-trigger', attrib={'stroke-width': 2} ), metadata ) # box, bounded by Q1 and Q3 alter( self.svg.node( parent_node, tag='rect', x=left_edge, y=self.view.y(quartiles[1]), height=self.view.y(quartiles[3]) - self.view.y(quartiles[1]), width=width, class_='subtle-fill reactive tooltip-trigger' ), metadata ) # draw outliers for o in outliers: alter( self.svg.node( parent_node, tag='circle', cx=left_edge + width / 2, cy=self.view.y(o), r=3, class_='subtle-fill reactive tooltip-trigger' ), metadata ) return ( left_edge + width / 2, self.view.y(sum(quartiles) / len(quartiles)) )
(self, parent_node, quartiles, outliers, box_index, metadata)
18,736
pygal.graph.box
_plot
Plot the series data
def _plot(self): """Plot the series data""" for serie in self.series: self._boxf(serie)
(self)
18,746
pygal.graph.box
_value_format
Format value for dual value display.
def _value_format(self, value, serie): """ Format value for dual value display. """ if self.box_mode == "extremes": return ( 'Min: %s\nQ1 : %s\nQ2 : %s\nQ3 : %s\nMax: %s' % tuple(map(self._y_format, serie.points[1:6])) ) elif self.box_mode in ["tukey", "stdev", "pstdev"]: return ( 'Min: %s\nLower Whisker: %s\nQ1: %s\nQ2: %s\nQ3: %s\n' 'Upper Whisker: %s\nMax: %s' % tuple(map(self._y_format, serie.points)) ) elif self.box_mode == '1.5IQR': # 1.5IQR mode return 'Q1: %s\nQ2: %s\nQ3: %s' % tuple( map(self._y_format, serie.points[2:5]) ) else: return self._y_format(serie.points)
(self, value, serie)
18,768
pygal.config
Config
Class holding config values
class Config(CommonConfig): """Class holding config values""" style = Key( DefaultStyle, Style, "Style", "Style holding values injected in css" ) css = Key( ('file://style.css', 'file://graph.css'), list, "Style", "List of css file", "It can be any uri from file:///tmp/style.css to //domain/style.css", str ) classes = Key(('pygal-chart', ), list, "Style", "Classes of the root svg node", str) defs = Key([], list, "Misc", "Extraneous defs to be inserted in svg", "Useful for adding gradients / patterns…", str) # Look # title = Key( None, str, "Look", "Graph title.", "Leave it to None to disable title." ) x_title = Key( None, str, "Look", "Graph X-Axis title.", "Leave it to None to disable X-Axis title." ) y_title = Key( None, str, "Look", "Graph Y-Axis title.", "Leave it to None to disable Y-Axis title." ) width = Key(800, int, "Look", "Graph width") height = Key(600, int, "Look", "Graph height") show_x_guides = Key( False, bool, "Look", "Set to true to always show x guide lines" ) show_y_guides = Key( True, bool, "Look", "Set to false to hide y guide lines" ) show_legend = Key(True, bool, "Look", "Set to false to remove legend") legend_at_bottom = Key( False, bool, "Look", "Set to true to position legend at bottom" ) legend_at_bottom_columns = Key( None, int, "Look", "Set to true to position legend at bottom" ) legend_box_size = Key(12, int, "Look", "Size of legend boxes") rounded_bars = Key( None, int, "Look", "Set this to the desired radius in px" ) stack_from_top = Key( False, bool, "Look", "Stack from top to zero, this makes the stacked " "data match the legend order" ) spacing = Key(10, int, "Look", "Space between titles/legend/axes") margin = Key(20, int, "Look", "Margin around chart") margin_top = Key(None, int, "Look", "Margin around top of chart") margin_right = Key(None, int, "Look", "Margin around right of chart") margin_bottom = Key(None, int, "Look", "Margin around bottom of chart") margin_left = Key(None, int, "Look", "Margin around left of chart") tooltip_border_radius = Key(0, int, "Look", "Tooltip border radius") tooltip_fancy_mode = Key( True, bool, "Look", "Fancy tooltips", "Print legend, x label in tooltip and use serie color for value." ) inner_radius = Key( 0, float, "Look", "Piechart inner radius (donut), must be <.9" ) half_pie = Key(False, bool, "Look", "Create a half-pie chart") x_labels = Key( None, list, "Label", "X labels, must have same len than data.", "Leave it to None to disable x labels display.", str ) x_labels_major = Key( None, list, "Label", "X labels that will be marked major.", subtype=str ) x_labels_major_every = Key( None, int, "Label", "Mark every n-th x label as major." ) x_labels_major_count = Key( None, int, "Label", "Mark n evenly distributed labels as major." ) show_x_labels = Key(True, bool, "Label", "Set to false to hide x-labels") show_minor_x_labels = Key( True, bool, "Label", "Set to false to hide x-labels not marked major" ) y_labels = Key( None, list, "Label", "You can specify explicit y labels", "Must be a list of numbers", float ) y_labels_major = Key( None, list, "Label", "Y labels that will be marked major. Default: auto", subtype=str ) y_labels_major_every = Key( None, int, "Label", "Mark every n-th y label as major." ) y_labels_major_count = Key( None, int, "Label", "Mark n evenly distributed y labels as major." ) show_minor_y_labels = Key( True, bool, "Label", "Set to false to hide y-labels not marked major" ) show_y_labels = Key(True, bool, "Label", "Set to false to hide y-labels") x_label_rotation = Key( 0, int, "Label", "Specify x labels rotation angles", "in degrees" ) y_label_rotation = Key( 0, int, "Label", "Specify y labels rotation angles", "in degrees" ) missing_value_fill_truncation = Key( "x", str, "Look", "Filled series with missing x and/or y values at the end of a series " "are closed at the first value with a missing " "'x' (default), 'y' or 'either'" ) # Value # x_value_formatter = Key( formatters.default, callable, "Value", "A function to convert abscissa numeric value to strings " "(used in XY and Date charts)" ) value_formatter = Key( formatters.default, callable, "Value", "A function to convert ordinate numeric value to strings" ) logarithmic = Key( False, bool, "Value", "Display values in logarithmic scale" ) interpolate = Key( None, str, "Value", "Interpolation", "May be %s" % ' or '.join(INTERPOLATIONS) ) interpolation_precision = Key( 250, int, "Value", "Number of interpolated points between two values" ) interpolation_parameters = Key( {}, dict, "Value", "Various parameters for parametric interpolations", "ie: For hermite interpolation, you can set the cardinal tension with" "{'type': 'cardinal', 'c': .5}", int ) box_mode = Key( 'extremes', str, "Value", "Sets the mode to be used. " "(Currently only supported on box plot)", "May be %s" % ' or '.join(["1.5IQR", "extremes", "tukey", "stdev", "pstdev"]) ) order_min = Key( None, int, "Value", "Minimum order of scale, defaults to None" ) min_scale = Key( 4, int, "Value", "Minimum number of scale graduation for auto scaling" ) max_scale = Key( 16, int, "Value", "Maximum number of scale graduation for auto scaling" ) range = Key( None, list, "Value", "Explicitly specify min and max of values", "(ie: (0, 100))", int ) secondary_range = Key( None, list, "Value", "Explicitly specify min and max of secondary values", "(ie: (0, 100))", int ) xrange = Key( None, list, "Value", "Explicitly specify min and max of x values " "(used in XY and Date charts)", "(ie: (0, 100))", int ) include_x_axis = Key(False, bool, "Value", "Always include x axis") zero = Key( 0, int, "Value", "Set the ordinate zero value", "Useful for filling to another base than abscissa" ) # Text # no_data_text = Key( "No data", str, "Text", "Text to display when no data is given" ) print_values = Key(False, bool, "Text", "Display values as text over plot") dynamic_print_values = Key( False, bool, "Text", "Show values only on hover" ) print_values_position = Key( 'center', str, "Text", "Customize position of `print_values`. " "(For bars: `top`, `center` or `bottom`)" ) print_zeroes = Key(True, bool, "Text", "Display zero values as well") print_labels = Key(False, bool, "Text", "Display value labels") truncate_legend = Key( None, int, "Text", "Legend string length truncation threshold", "None = auto, Negative for none" ) truncate_label = Key( None, int, "Text", "Label string length truncation threshold", "None = auto, Negative for none" ) # Misc # js = Key(('//kozea.github.io/pygal.js/2.0.x/pygal-tooltips.min.js', ), list, "Misc", "List of js file", "It can be any uri from file:///tmp/ext.js to //domain/ext.js", str) disable_xml_declaration = Key( False, bool, "Misc", "Don't write xml declaration and return str instead of string", "useful for writing output directly in html" ) force_uri_protocol = Key( 'https', str, "Misc", "Default uri protocol", "Default protocol for external files. " "Can be set to None to use a // uri" ) explicit_size = Key( False, bool, "Misc", "Write width and height attributes" ) pretty_print = Key(False, bool, "Misc", "Pretty print the svg") strict = Key( False, bool, "Misc", "If True don't try to adapt / filter wrong values" ) no_prefix = Key(False, bool, "Misc", "Don't prefix css") inverse_y_axis = Key(False, bool, "Misc", "Inverse Y axis direction")
(**kwargs)
18,769
pygal.config
__call__
Can be updated with kwargs
def __call__(self, **kwargs): """Can be updated with kwargs""" self._update(kwargs)
(self, **kwargs)
18,770
pygal.config
__init__
Can be instanciated with config kwargs
def __init__(self, **kwargs): """Can be instanciated with config kwargs""" for k in dir(self): v = getattr(self, k) if (k not in self.__dict__ and not k.startswith('_') and not hasattr(v, '__call__')): if isinstance(v, Key): if v.is_list and v.value is not None: v = list(v.value) else: v = v.value setattr(self, k, v) self._update(kwargs)
(self, **kwargs)
18,771
pygal.config
_update
Update the config with the given dictionary
def _update(self, kwargs): """Update the config with the given dictionary""" from pygal.util import merge dir_self_set = set(dir(self)) merge( self.__dict__, dict([(k, v) for (k, v) in kwargs.items() if not k.startswith('_') and k in dir_self_set]) )
(self, kwargs)
18,772
pygal.config
copy
Copy this config object into another
def copy(self): """Copy this config object into another""" return deepcopy(self)
(self)
18,773
pygal.config
to_dict
Export a JSON serializable dictionary of the config
def to_dict(self): """Export a JSON serializable dictionary of the config""" config = {} for attr in dir(self): if not attr.startswith('__'): value = getattr(self, attr) if hasattr(value, 'to_dict'): config[attr] = value.to_dict() elif not hasattr(value, '__call__'): config[attr] = value return config
(self)
18,774
pygal.graph.time
DateLine
Date abscissa xy graph class
class DateLine(DateTimeLine): """Date abscissa xy graph class""" @property def _x_format(self): """Return the value formatter for this graph""" def date_to_str(x): d = datetime.utcfromtimestamp(x).date() return self.x_value_formatter(d) return date_to_str
(*args, **kwargs)
18,777
pygal.graph.line
__init__
Set _self_close as False, it's True for Radar like Line
def __init__(self, *args, **kwargs): """Set _self_close as False, it's True for Radar like Line""" self._self_close = False super(Line, self).__init__(*args, **kwargs)
(self, *args, **kwargs)
18,780
pygal.graph.xy
_compute
Compute x/y min and max and x/y scale and set labels
def _compute(self): """Compute x/y min and max and x/y scale and set labels""" if self.xvals: if self.xrange: x_adapter = reduce(compose, self._x_adapters) if getattr( self, '_x_adapters', None ) else ident xmin = x_adapter(self.xrange[0]) xmax = x_adapter(self.xrange[1]) else: xmin = min(self.xvals) xmax = max(self.xvals) xrng = (xmax - xmin) else: xrng = None if self.yvals: ymin = self._min ymax = self._max if self.include_x_axis: ymin = min(ymin or 0, 0) ymax = max(ymax or 0, 0) yrng = (ymax - ymin) else: yrng = None for serie in self.all_series: serie.points = serie.values if self.interpolate: vals = list( zip( *sorted( filter(lambda t: None not in t, serie.points), key=lambda x: x[0] ) ) ) serie.interpolated = self._interpolate(vals[0], vals[1]) if self.interpolate: self.xvals = [ val[0] for serie in self.all_series for val in serie.interpolated ] self.yvals = [ val[1] for serie in self.series for val in serie.interpolated ] if self.xvals: xmin = min(self.xvals) xmax = max(self.xvals) xrng = (xmax - xmin) else: xrng = None # these values can also be 0 (zero), so testing explicitly for None if xrng is not None: self._box.xmin, self._box.xmax = xmin, xmax if yrng is not None: self._box.ymin, self._box.ymax = ymin, ymax
(self)
18,783
pygal.graph.dual
_compute_x_labels
null
def _compute_x_labels(self): x_pos = compute_scale( self._box.xmin, self._box.xmax, self.logarithmic, self.order_min, self.min_scale, self.max_scale ) if self.x_labels: self._x_labels = [] for i, x_label in enumerate(self.x_labels): if isinstance(x_label, dict): pos = self._x_adapt(x_label.get('value')) title = x_label.get('label', self._x_format(pos)) elif is_str(x_label): pos = self._x_adapt(x_pos[i % len(x_pos)]) title = x_label else: pos = self._x_adapt(x_label) title = self._x_format(pos) self._x_labels.append((title, pos)) self._box.xmin = min(self._box.xmin, min(cut(self._x_labels, 1))) self._box.xmax = max(self._box.xmax, max(cut(self._x_labels, 1))) else: self._x_labels = list(zip(map(self._x_format, x_pos), x_pos))
(self)
18,784
pygal.graph.dual
_compute_x_labels_major
null
def _compute_x_labels_major(self): # In case of dual, x labels must adapters and so majors too self.x_labels_major = self.x_labels_major and list( map(self._x_adapt, self.x_labels_major) ) super(Dual, self)._compute_x_labels_major()
(self)