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,790
pygal.graph.line
_fill
Add extra values to fill the line
def _fill(self, values): """Add extra values to fill the line""" zero = self.view.y(min(max(self.zero, self._box.ymin), self._box.ymax)) # Check to see if the data has been padded with "none's" # Fill doesn't work correctly otherwise end = len(values) - 1 while end > 0: x, y = values[end] if self.missing_value_fill_truncation == "either": if x is not None and y is not None: break elif self.missing_value_fill_truncation == "x": if x is not None: break elif self.missing_value_fill_truncation == "y": if y is not None: break else: raise ValueError( "Invalid value ({}) for config key " "'missing_value_fill_truncation';" " Use 'x', 'y' or 'either'".format( self.missing_value_fill_truncation ) ) end -= 1 return ([(values[0][0], zero)] + values + [(values[end][0], zero)])
(self, values)
18,792
pygal.graph.dual
_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""" return
(self, i)
18,800
pygal.graph.line
_plot
Plot the serie lines and secondary serie lines
def _plot(self): """Plot the serie lines and secondary serie lines""" for serie in self.series: self.line(serie) for serie in self.secondary_series: self.line(serie, True)
(self)
18,810
pygal.graph.dual
_value_format
Format value for dual value display.
def _value_format(self, value): """ Format value for dual value display. """ return '%s: %s' % (self._x_format(value[0]), self._y_format(value[1]))
(self, value)
18,817
pygal.graph.line
line
Draw the line serie
def line(self, serie, rescale=False): """Draw the line serie""" serie_node = self.svg.serie(serie) if rescale and self.secondary_series: points = self._rescale(serie.points) else: points = serie.points view_values = list(map(self.view, points)) if serie.show_dots: for i, (x, y) in enumerate(view_values): if None in (x, y): continue if self.logarithmic: if points[i][1] is None or points[i][1] <= 0: continue if (serie.show_only_major_dots and self.x_labels and i < len(self.x_labels) and self.x_labels[i] not in self._x_labels_major): continue metadata = serie.metadata.get(i) classes = [] if x > self.view.width / 2: classes.append('left') if y > self.view.height / 2: classes.append('top') classes = ' '.join(classes) self._confidence_interval( serie_node['overlay'], x, y, serie.values[i], metadata ) dots = decorate( self.svg, self.svg.node(serie_node['overlay'], class_="dots"), metadata ) val = self._format(serie, i) alter( self.svg.transposable_node( dots, 'circle', cx=x, cy=y, r=serie.dots_size, class_='dot reactive tooltip-trigger' ), metadata ) self._tooltip_data( dots, val, x, y, xlabel=self._get_x_label(i) ) self._static_value( serie_node, val, x + self.style.value_font_size, y + self.style.value_font_size, metadata ) if serie.stroke: if self.interpolate: points = serie.interpolated if rescale and self.secondary_series: points = self._rescale(points) view_values = list(map(self.view, points)) if serie.fill: view_values = self._fill(view_values) if serie.allow_interruptions: # view_values are in form [(x1, y1), (x2, y2)]. We # need to split that into multiple sequences if a # None is present here sequences = [] cur_sequence = [] for x, y in view_values: if y is None and len(cur_sequence) > 0: # emit current subsequence sequences.append(cur_sequence) cur_sequence = [] elif y is None: # just discard continue else: cur_sequence.append((x, y)) # append the element if len(cur_sequence) > 0: # emit last possible sequence sequences.append(cur_sequence) else: # plain vanilla rendering sequences = [view_values] if self.logarithmic: for seq in sequences: for ele in seq[::-1]: y = points[seq.index(ele)][1] if y is None or y <= 0: del seq[seq.index(ele)] for seq in sequences: self.svg.line( serie_node['plot'], seq, close=self._self_close, class_='line reactive' + (' nofill' if not serie.fill else '') )
(self, serie, rescale=False)
18,833
pygal.graph.time
DateTimeLine
DateTime abscissa xy graph class
class DateTimeLine(XY): """DateTime abscissa xy graph class""" _x_adapters = [datetime_to_timestamp, date_to_datetime] @property def _x_format(self): """Return the value formatter for this graph""" def datetime_to_str(x): dt = datetime.utcfromtimestamp(x) return self.x_value_formatter(dt) return datetime_to_str
(*args, **kwargs)
18,892
pygal.graph.dot
Dot
Dot graph class
class Dot(Graph): """Dot graph class""" def dot(self, serie, r_max): """Draw a dot line""" serie_node = self.svg.serie(serie) view_values = list(map(self.view, serie.points)) for i, value in safe_enumerate(serie.values): x, y = view_values[i] if self.logarithmic: log10min = log10(self._min) - 1 log10max = log10(self._max or 1) if value != 0: size = r_max * ((log10(abs(value)) - log10min) / (log10max - log10min)) else: size = 0 else: size = r_max * (abs(value) / (self._max or 1)) metadata = serie.metadata.get(i) dots = decorate( self.svg, self.svg.node(serie_node['plot'], class_="dots"), metadata ) alter( self.svg.node( dots, 'circle', cx=x, cy=y, r=size, class_='dot reactive tooltip-trigger' + (' negative' if value < 0 else '') ), metadata ) val = self._format(serie, i) self._tooltip_data( dots, val, x, y, 'centered', self._get_x_label(i) ) self._static_value(serie_node, val, x, y, metadata) def _compute(self): """Compute y min and max and y scale and set labels""" x_len = self._len y_len = self._order self._box.xmax = x_len self._box.ymax = y_len self._x_pos = [n / 2 for n in range(1, 2 * x_len, 2)] self._y_pos = [n / 2 for n in reversed(range(1, 2 * y_len, 2))] for j, serie in enumerate(self.series): serie.points = [(self._x_pos[i], self._y_pos[j]) for i in range(x_len)] def _compute_y_labels(self): self._y_labels = list( zip( self.y_labels and map(to_str, self.y_labels) or [ serie.title['title'] if isinstance(serie.title, dict) else serie.title or '' for serie in self.series ], self._y_pos ) ) def _set_view(self): """Assign a view to current graph""" 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 ) @cached_property def _values(self): """Getter for series values (flattened)""" return [abs(val) for val in super(Dot, self)._values if val != 0] @cached_property def _max(self): """Getter for the maximum series value""" return ( self.range[1] if (self.range and self.range[1] is not None) else (max(map(abs, self._values)) if self._values else None) ) def _plot(self): """Plot all dots for series""" r_max = min( self.view.x(1) - self.view.x(0), (self.view.y(0) or 0) - self.view.y(1) ) / (2 * 1.05) for serie in self.series: self.dot(serie, r_max)
(config=None, **kwargs)
18,898
pygal.graph.dot
_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""" x_len = self._len y_len = self._order self._box.xmax = x_len self._box.ymax = y_len self._x_pos = [n / 2 for n in range(1, 2 * x_len, 2)] self._y_pos = [n / 2 for n in reversed(range(1, 2 * y_len, 2))] for j, serie in enumerate(self.series): serie.points = [(self._x_pos[i], self._y_pos[j]) for i in range(x_len)]
(self)
18,903
pygal.graph.dot
_compute_y_labels
null
def _compute_y_labels(self): self._y_labels = list( zip( self.y_labels and map(to_str, self.y_labels) or [ serie.title['title'] if isinstance(serie.title, dict) else serie.title or '' for serie in self.series ], self._y_pos ) )
(self)
18,917
pygal.graph.dot
_plot
Plot all dots for series
def _plot(self): """Plot all dots for series""" r_max = min( self.view.x(1) - self.view.x(0), (self.view.y(0) or 0) - self.view.y(1) ) / (2 * 1.05) for serie in self.series: self.dot(serie, r_max)
(self)
18,924
pygal.graph.dot
_set_view
Assign a view to current graph
def _set_view(self): """Assign a view to current graph""" 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,934
pygal.graph.dot
dot
Draw a dot line
def dot(self, serie, r_max): """Draw a dot line""" serie_node = self.svg.serie(serie) view_values = list(map(self.view, serie.points)) for i, value in safe_enumerate(serie.values): x, y = view_values[i] if self.logarithmic: log10min = log10(self._min) - 1 log10max = log10(self._max or 1) if value != 0: size = r_max * ((log10(abs(value)) - log10min) / (log10max - log10min)) else: size = 0 else: size = r_max * (abs(value) / (self._max or 1)) metadata = serie.metadata.get(i) dots = decorate( self.svg, self.svg.node(serie_node['plot'], class_="dots"), metadata ) alter( self.svg.node( dots, 'circle', cx=x, cy=y, r=size, class_='dot reactive tooltip-trigger' + (' negative' if value < 0 else '') ), metadata ) val = self._format(serie, i) self._tooltip_data( dots, val, x, y, 'centered', self._get_x_label(i) ) self._static_value(serie_node, val, x, y, metadata)
(self, serie, r_max)
18,950
pygal.graph.funnel
Funnel
Funnel graph class
class Funnel(Graph): """Funnel graph class""" _adapters = [positive, none_to_zero] def _value_format(self, value): """Format value for dual value display.""" return super(Funnel, self)._value_format(value and abs(value)) def funnel(self, serie): """Draw a funnel slice""" serie_node = self.svg.serie(serie) fmt = lambda x: '%f %f' % x for i, poly in enumerate(serie.points): metadata = serie.metadata.get(i) val = self._format(serie, i) funnels = decorate( self.svg, self.svg.node(serie_node['plot'], class_="funnels"), metadata ) alter( self.svg.node( funnels, 'polygon', points=' '.join(map(fmt, map(self.view, poly))), class_='funnel reactive tooltip-trigger' ), metadata ) # Poly center from label x, y = self.view(( self._center(self._x_pos[serie.index]), sum([point[1] for point in poly]) / len(poly) )) self._tooltip_data( funnels, val, x, y, 'centered', self._get_x_label(serie.index) ) self._static_value(serie_node, val, x, y, metadata) def _center(self, x): return x - 1 / (2 * self._order) def _compute(self): """Compute y min and max and y scale and set labels""" self._x_pos = [ (x + 1) / self._order for x in range(self._order) ] if self._order != 1 else [.5] # Center if only one value previous = [[self.zero, self.zero] for i in range(self._len)] for i, serie in enumerate(self.series): y_height = -sum(serie.safe_values) / 2 all_x_pos = [0] + self._x_pos serie.points = [] for j, value in enumerate(serie.values): poly = [] poly.append((all_x_pos[i], previous[j][0])) poly.append((all_x_pos[i], previous[j][1])) previous[j][0] = y_height y_height = previous[j][1] = y_height + value poly.append((all_x_pos[i + 1], previous[j][1])) poly.append((all_x_pos[i + 1], previous[j][0])) serie.points.append(poly) val_max = max(list(map(sum, cut(self.series, 'values'))) + [self.zero]) self._box.ymin = -val_max self._box.ymax = val_max if self.range and self.range[0] is not None: self._box.ymin = self.range[0] if self.range and self.range[1] is not None: self._box.ymax = self.range[1] def _compute_x_labels(self): self._x_labels = list( zip( self.x_labels and map(self._x_format, self.x_labels) or [ serie.title['title'] if isinstance(serie.title, dict) else serie.title or '' for serie in self.series ], map(self._center, self._x_pos) ) ) def _plot(self): """Plot the funnel""" for serie in self.series: self.funnel(serie)
(config=None, **kwargs)
18,956
pygal.graph.funnel
_center
null
def _center(self, x): return x - 1 / (2 * self._order)
(self, x)
18,957
pygal.graph.funnel
_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""" self._x_pos = [ (x + 1) / self._order for x in range(self._order) ] if self._order != 1 else [.5] # Center if only one value previous = [[self.zero, self.zero] for i in range(self._len)] for i, serie in enumerate(self.series): y_height = -sum(serie.safe_values) / 2 all_x_pos = [0] + self._x_pos serie.points = [] for j, value in enumerate(serie.values): poly = [] poly.append((all_x_pos[i], previous[j][0])) poly.append((all_x_pos[i], previous[j][1])) previous[j][0] = y_height y_height = previous[j][1] = y_height + value poly.append((all_x_pos[i + 1], previous[j][1])) poly.append((all_x_pos[i + 1], previous[j][0])) serie.points.append(poly) val_max = max(list(map(sum, cut(self.series, 'values'))) + [self.zero]) self._box.ymin = -val_max self._box.ymax = val_max if self.range and self.range[0] is not None: self._box.ymin = self.range[0] if self.range and self.range[1] is not None: self._box.ymax = self.range[1]
(self)
18,960
pygal.graph.funnel
_compute_x_labels
null
def _compute_x_labels(self): self._x_labels = list( zip( self.x_labels and map(self._x_format, self.x_labels) or [ serie.title['title'] if isinstance(serie.title, dict) else serie.title or '' for serie in self.series ], map(self._center, self._x_pos) ) )
(self)
18,976
pygal.graph.funnel
_plot
Plot the funnel
def _plot(self): """Plot the funnel""" for serie in self.series: self.funnel(serie)
(self)
18,986
pygal.graph.funnel
_value_format
Format value for dual value display.
def _value_format(self, value): """Format value for dual value display.""" return super(Funnel, self)._value_format(value and abs(value))
(self, value)
18,993
pygal.graph.funnel
funnel
Draw a funnel slice
def funnel(self, serie): """Draw a funnel slice""" serie_node = self.svg.serie(serie) fmt = lambda x: '%f %f' % x for i, poly in enumerate(serie.points): metadata = serie.metadata.get(i) val = self._format(serie, i) funnels = decorate( self.svg, self.svg.node(serie_node['plot'], class_="funnels"), metadata ) alter( self.svg.node( funnels, 'polygon', points=' '.join(map(fmt, map(self.view, poly))), class_='funnel reactive tooltip-trigger' ), metadata ) # Poly center from label x, y = self.view(( self._center(self._x_pos[serie.index]), sum([point[1] for point in poly]) / len(poly) )) self._tooltip_data( funnels, val, x, y, 'centered', self._get_x_label(serie.index) ) self._static_value(serie_node, val, x, y, metadata)
(self, serie)
19,009
pygal.graph.gauge
Gauge
Gauge graph class
class Gauge(Graph): """Gauge graph class""" needle_width = 1 / 20 def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarThetaLogView else: view_class = PolarThetaView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ) def needle(self, serie): """Draw a needle for each value""" serie_node = self.svg.serie(serie) for i, theta in enumerate(serie.values): if theta is None: continue def point(x, y): return '%f %f' % self.view((x, y)) val = self._format(serie, i) metadata = serie.metadata.get(i) gauges = decorate( self.svg, self.svg.node(serie_node['plot'], class_="dots"), metadata ) tolerance = 1.15 if theta < self._min: theta = self._min * tolerance if theta > self._max: theta = self._max * tolerance w = (self._box._tmax - self._box._tmin + self.view.aperture) / 4 if self.logarithmic: w = min(w, self._min - self._min * 10**-10) alter( self.svg.node( gauges, 'path', d='M %s L %s A %s 1 0 1 %s Z' % ( point(.85, theta), point(self.needle_width, theta - w), '%f %f' % (self.needle_width, self.needle_width), point(self.needle_width, theta + w), ), class_='line reactive tooltip-trigger' ), metadata ) x, y = self.view((.75, theta)) self._tooltip_data(gauges, val, x, y, xlabel=self._get_x_label(i)) self._static_value(serie_node, val, x, y, metadata) def _y_axis(self, draw_axes=True): """Override y axis to plot a polar axis""" axis = self.svg.node(self.nodes['plot'], class_="axis x gauge") for i, (label, theta) in enumerate(self._y_labels): guides = self.svg.node(axis, class_='guides') self.svg.line( guides, [self.view((.95, theta)), self.view((1, theta))], close=True, class_='line' ) self.svg.line( guides, [self.view((0, theta)), self.view((.95, theta))], close=True, class_='guide line %s' % ('major' if i in (0, len(self._y_labels) - 1) else '') ) x, y = self.view((.9, theta)) self.svg.node(guides, 'text', x=x, y=y).text = label self.svg.node( guides, 'title', ).text = self._y_format(theta) def _x_axis(self, draw_axes=True): """Override x axis to put a center circle in center""" axis = self.svg.node(self.nodes['plot'], class_="axis y gauge") x, y = self.view((0, 0)) self.svg.node(axis, 'circle', cx=x, cy=y, r=4) def _compute(self): """Compute y min and max and y scale and set labels""" self.min_ = self._min or 0 self.max_ = self._max or 0 if self.max_ - self.min_ == 0: self.min_ -= 1 self.max_ += 1 self._box.set_polar_box(0, 1, self.min_, self.max_) def _compute_x_labels(self): pass def _compute_y_labels(self): y_pos = compute_scale( self.min_, self.max_, 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]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self.min_ = min(self.min_, min(cut(self._y_labels, 1))) self.max_ = max(self.max_, max(cut(self._y_labels, 1))) self._box.set_polar_box(0, 1, self.min_, self.max_) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos)) def _plot(self): """Plot all needles""" for serie in self.series: self.needle(serie)
(config=None, **kwargs)
19,015
pygal.graph.gauge
_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""" self.min_ = self._min or 0 self.max_ = self._max or 0 if self.max_ - self.min_ == 0: self.min_ -= 1 self.max_ += 1 self._box.set_polar_box(0, 1, self.min_, self.max_)
(self)
19,020
pygal.graph.gauge
_compute_y_labels
null
def _compute_y_labels(self): y_pos = compute_scale( self.min_, self.max_, 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]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self.min_ = min(self.min_, min(cut(self._y_labels, 1))) self.max_ = max(self.max_, max(cut(self._y_labels, 1))) self._box.set_polar_box(0, 1, self.min_, self.max_) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos))
(self)
19,034
pygal.graph.gauge
_plot
Plot all needles
def _plot(self): """Plot all needles""" for serie in self.series: self.needle(serie)
(self)
19,041
pygal.graph.gauge
_set_view
Assign a view to current graph
def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarThetaLogView else: view_class = PolarThetaView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box )
(self)
19,045
pygal.graph.gauge
_x_axis
Override x axis to put a center circle in center
def _x_axis(self, draw_axes=True): """Override x axis to put a center circle in center""" axis = self.svg.node(self.nodes['plot'], class_="axis y gauge") x, y = self.view((0, 0)) self.svg.node(axis, 'circle', cx=x, cy=y, r=4)
(self, draw_axes=True)
19,047
pygal.graph.gauge
_y_axis
Override y axis to plot a polar axis
def _y_axis(self, draw_axes=True): """Override y axis to plot a polar axis""" axis = self.svg.node(self.nodes['plot'], class_="axis x gauge") for i, (label, theta) in enumerate(self._y_labels): guides = self.svg.node(axis, class_='guides') self.svg.line( guides, [self.view((.95, theta)), self.view((1, theta))], close=True, class_='line' ) self.svg.line( guides, [self.view((0, theta)), self.view((.95, theta))], close=True, class_='guide line %s' % ('major' if i in (0, len(self._y_labels) - 1) else '') ) x, y = self.view((.9, theta)) self.svg.node(guides, 'text', x=x, y=y).text = label self.svg.node( guides, 'title', ).text = self._y_format(theta)
(self, draw_axes=True)
19,051
pygal.graph.gauge
needle
Draw a needle for each value
def needle(self, serie): """Draw a needle for each value""" serie_node = self.svg.serie(serie) for i, theta in enumerate(serie.values): if theta is None: continue def point(x, y): return '%f %f' % self.view((x, y)) val = self._format(serie, i) metadata = serie.metadata.get(i) gauges = decorate( self.svg, self.svg.node(serie_node['plot'], class_="dots"), metadata ) tolerance = 1.15 if theta < self._min: theta = self._min * tolerance if theta > self._max: theta = self._max * tolerance w = (self._box._tmax - self._box._tmin + self.view.aperture) / 4 if self.logarithmic: w = min(w, self._min - self._min * 10**-10) alter( self.svg.node( gauges, 'path', d='M %s L %s A %s 1 0 1 %s Z' % ( point(.85, theta), point(self.needle_width, theta - w), '%f %f' % (self.needle_width, self.needle_width), point(self.needle_width, theta + w), ), class_='line reactive tooltip-trigger' ), metadata ) x, y = self.view((.75, theta)) self._tooltip_data(gauges, val, x, y, xlabel=self._get_x_label(i)) self._static_value(serie_node, val, x, y, metadata)
(self, serie)
19,067
pygal.graph.graph
Graph
Graph super class containing generic common functions
class Graph(PublicApi): """Graph super class containing generic common functions""" _dual = False 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() def _axes(self): """Draw axes""" self._y_axis() self._x_axis() 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 ) 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') 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']) 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']) 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 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 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 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 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 ) ) 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] 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) 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 '' 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 = [] 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 def _post_compute(self): """Hook called after compute and before margin computations and plot""" pass 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] @property def all_series(self): """Getter for all series (nomal and secondary)""" return self.series + self.secondary_series @property def _x_format(self): """Return the abscissa value formatter (always unary)""" return self.x_value_formatter @property def _default_formatter(self): return to_str @property def _y_format(self): """Return the ordinate value formatter (always unary)""" return self.value_formatter def _value_format(self, value): """ Format value for value display. (Varies in type between chart types) """ return self._y_format(value) 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) 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) def _compute(self): """Initial computations to draw the graph""" 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 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)) ) @cached_property def _legends(self): """Getter for series title""" return [serie.title for serie in self.series] @cached_property def _secondary_legends(self): """Getter for series title on secondary y axis""" return [serie.title for serie in self.secondary_series] @cached_property def _values(self): """Getter for series values (flattened)""" return [ val for serie in self.series for val in serie.values if val is not None ] @cached_property def _secondary_values(self): """Getter for secondary series values (flattened)""" return [ val for serie in self.secondary_series for val in serie.values if val is not None ] @cached_property def _len(self): """Getter for the maximum series size""" return max([len(serie.values) for serie in self.all_series] or [0]) @cached_property def _secondary_min(self): """Getter for the minimum series value""" return ( self.secondary_range[0] if (self.secondary_range and self.secondary_range[0] is not None) else (min(self._secondary_values) if self._secondary_values else None) ) @cached_property def _min(self): """Getter for the minimum series value""" return ( self.range[0] if (self.range and self.range[0] is not None) else (min(self._values) if self._values else None) ) @cached_property def _max(self): """Getter for the maximum series value""" return ( self.range[1] if (self.range and self.range[1] is not None) else (max(self._values) if self._values else None) ) @cached_property def _secondary_max(self): """Getter for the maximum series value""" return ( self.secondary_range[1] if (self.secondary_range and self.secondary_range[1] is not None) else (max(self._secondary_values) if self._secondary_values else None) ) @cached_property def _order(self): """Getter for the number of series""" return len(self.all_series) def _x_label_format_if_value(self, label): if not is_str(label): return self._x_format(label) return label 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 ) ) 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 [] 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)) 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 = [] 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]) 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() 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 ])
(config=None, **kwargs)
19,123
pygal.graph.histogram
Histogram
Histogram chart class
class Histogram(Dual, Bar): """Histogram chart class""" _series_margin = 0 @cached_property def _values(self): """Getter for secondary series values (flattened)""" return self.yvals @cached_property def _secondary_values(self): """Getter for secondary series values (flattened)""" return [ val[0] for serie in self.secondary_series for val in serie.values if val[0] is not None ] @cached_property def xvals(self): """All x values""" return [ val for serie in self.all_series for dval in serie.values for val in dval[1:3] if val is not None ] @cached_property def yvals(self): """All y values""" return [ val[0] for serie in self.series for val in serie.values if val[0] is not None ] def _bar(self, serie, parent, x0, x1, y, i, zero, secondary=False): """Internal bar drawing function""" x, y = self.view((x0, y)) x1, _ = self.view((x1, y)) width = x1 - x height = self.view.y(zero) - y series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin 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 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_="histbars") points = serie.points for i, (y, x0, x1) in enumerate(points): if None in (x0, x1, y) or (self.logarithmic and y <= 0): continue metadata = serie.metadata.get(i) bar = decorate( self.svg, self.svg.node(bars, class_='histbar'), metadata ) val = self._format(serie, i) bounds = self._bar( serie, bar, x0, x1, y, i, self.zero, secondary=rescale ) self._tooltip_and_print_values( serie_node, serie, bar, i, val, metadata, *bounds ) def _compute(self): """Compute x/y min and max and x/y scale and set labels""" if self.xvals: xmin = min(self.xvals) xmax = max(self.xvals) xrng = (xmax - xmin) else: xrng = None if self.yvals: ymin = min(min(self.yvals), self.zero) ymax = max(max(self.yvals), self.zero) yrng = (ymax - ymin) else: yrng = None for serie in self.all_series: serie.points = serie.values if xrng: self._box.xmin, self._box.xmax = xmin, xmax if yrng: self._box.ymin, self._box.ymax = ymin, ymax if self.range and self.range[0] is not None: self._box.ymin = self.range[0] if self.range and self.range[1] is not None: self._box.ymax = self.range[1]
(config=None, **kwargs)
19,129
pygal.graph.histogram
_bar
Internal bar drawing function
def _bar(self, serie, parent, x0, x1, y, i, zero, secondary=False): """Internal bar drawing function""" x, y = self.view((x0, y)) x1, _ = self.view((x1, y)) width = x1 - x height = self.view.y(zero) - y series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin 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, x0, x1, y, i, zero, secondary=False)
19,130
pygal.graph.histogram
_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: xmin = min(self.xvals) xmax = max(self.xvals) xrng = (xmax - xmin) else: xrng = None if self.yvals: ymin = min(min(self.yvals), self.zero) ymax = max(max(self.yvals), self.zero) yrng = (ymax - ymin) else: yrng = None for serie in self.all_series: serie.points = serie.values if xrng: self._box.xmin, self._box.xmax = xmin, xmax if yrng: self._box.ymin, self._box.ymax = ymin, ymax if self.range and self.range[0] is not None: self._box.ymin = self.range[0] if self.range and self.range[1] is not None: self._box.ymax = self.range[1]
(self)
19,167
pygal.graph.histogram
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_="histbars") points = serie.points for i, (y, x0, x1) in enumerate(points): if None in (x0, x1, y) or (self.logarithmic and y <= 0): continue metadata = serie.metadata.get(i) bar = decorate( self.svg, self.svg.node(bars, class_='histbar'), metadata ) val = self._format(serie, i) bounds = self._bar( serie, bar, x0, x1, y, i, self.zero, secondary=rescale ) self._tooltip_and_print_values( serie_node, serie, bar, i, val, metadata, *bounds )
(self, serie, rescale=False)
19,183
pygal.graph.horizontalbar
HorizontalBar
Horizontal Bar graph
class HorizontalBar(HorizontalGraph, Bar): """Horizontal Bar graph""" def _plot(self): """Draw the bars in reverse order""" for serie in self.series[::-1]: self.bar(serie) for serie in self.secondary_series[::-1]: self.bar(serie, True)
(*args, **kwargs)
19,186
pygal.graph.horizontal
__init__
Set the horizontal flag to True
def __init__(self, *args, **kwargs): """Set the horizontal flag to True""" self.horizontal = True super(HorizontalGraph, self).__init__(*args, **kwargs)
(self, *args, **kwargs)
19,188
pygal.graph.horizontal
_axes
Set the _force_vertical flag when rendering axes
def _axes(self): """Set the _force_vertical flag when rendering axes""" self.view._force_vertical = True super(HorizontalGraph, self)._axes() self.view._force_vertical = False
(self)
19,201
pygal.graph.horizontal
_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._y_labels or len(self._y_labels) <= i: return return self._y_labels[i][0]
(self, i)
19,209
pygal.graph.horizontalbar
_plot
Draw the bars in reverse order
def _plot(self): """Draw the bars in reverse order""" for serie in self.series[::-1]: self.bar(serie) for serie in self.secondary_series[::-1]: self.bar(serie, True)
(self)
19,211
pygal.graph.horizontal
_post_compute
After computations transpose labels
def _post_compute(self): """After computations transpose labels""" self._x_labels, self._y_labels = self._y_labels, self._x_labels self._x_labels_major, self._y_labels_major = ( self._y_labels_major, self._x_labels_major ) self._x_2nd_labels, self._y_2nd_labels = ( self._y_2nd_labels, self._x_2nd_labels ) self.show_y_guides, self.show_x_guides = ( self.show_x_guides, self.show_y_guides )
(self)
19,216
pygal.graph.horizontal
_set_view
Assign a horizontal view to current graph
def _set_view(self): """Assign a horizontal view to current graph""" if self.logarithmic: view_class = HorizontalLogView else: view_class = HorizontalView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box )
(self)
19,243
pygal.graph.horizontalline
HorizontalLine
Horizontal Line graph
class HorizontalLine(HorizontalGraph, Line): """Horizontal Line graph""" def _plot(self): """Draw the lines in reverse order""" for serie in self.series[::-1]: self.line(serie) for serie in self.secondary_series[::-1]: self.line(serie, True)
(*args, **kwargs)
19,249
pygal.graph.line
_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""" # X Labels if self.horizontal: self._x_pos = [ x / (self._len - 1) for x in range(self._len) ][::-1] if self._len != 1 else [.5] # Center if only one value else: self._x_pos = [ x / (self._len - 1) for x in range(self._len) ] if self._len != 1 else [.5] # Center if only one value self._points(self._x_pos) if self.include_x_axis: # Y Label self._box.ymin = min(self._min or 0, 0) self._box.ymax = max(self._max or 0, 0) else: self._box.ymin = self._min self._box.ymax = self._max
(self)
19,269
pygal.graph.horizontalline
_plot
Draw the lines in reverse order
def _plot(self): """Draw the lines in reverse order""" for serie in self.series[::-1]: self.line(serie) for serie in self.secondary_series[::-1]: self.line(serie, True)
(self)
19,302
pygal.graph.horizontalstackedbar
HorizontalStackedBar
Horizontal Stacked Bar graph
class HorizontalStackedBar(HorizontalGraph, StackedBar): """Horizontal Stacked Bar graph"""
(*args, **kwargs)
19,308
pygal.graph.stackedbar
_bar
Internal stacking bar drawing function
def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal stacking bar drawing function""" if secondary: cumulation = ( self.secondary_negative_cumulation if y < self.zero else self.secondary_positive_cumulation ) else: cumulation = ( self.negative_cumulation if y < self.zero else self.positive_cumulation ) zero = cumulation[i] cumulation[i] = zero + y if zero == 0: zero = self.zero y -= self.zero y += zero width = (self.view.x(1) - self.view.x(0)) / self._len x, y = self.view((x, y)) y = y or 0 series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin if self.secondary_series: width /= 2 x += int(secondary) * 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 self.svg.transposable_node( parent, 'rect', x=x, y=y, rx=r, ry=r, width=width, height=height, class_='rect reactive tooltip-trigger' ) return x, y, width, height
(self, serie, parent, x, y, i, zero, secondary=False)
19,309
pygal.graph.stackedbar
_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""" positive_vals, negative_vals = self._get_separated_values() if self.logarithmic: positive_vals = list( filter(lambda x: x > self.zero, positive_vals) ) negative_vals = list( filter(lambda x: x > self.zero, negative_vals) ) self._compute_box(positive_vals, negative_vals) positive_vals = positive_vals or [self.zero] negative_vals = negative_vals or [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.negative_cumulation = [0] * self._len self.positive_cumulation = [0] * self._len if self.secondary_series: positive_vals, negative_vals = self._get_separated_values(True) positive_vals = positive_vals or [self.zero] negative_vals = negative_vals or [self.zero] self.secondary_negative_cumulation = [0] * self._len self.secondary_positive_cumulation = [0] * self._len self._pre_compute_secondary(positive_vals, negative_vals) self._x_pos = [(i + .5) / self._len for i in range(self._len)]
(self)
19,310
pygal.graph.stackedbar
_compute_box
Compute Y min and max
def _compute_box(self, positive_vals, negative_vals): """Compute Y min and max""" if self.range and self.range[0] is not None: self._box.ymin = self.range[0] else: self._box.ymin = negative_vals and min( min(negative_vals), self.zero ) or self.zero if self.range and self.range[1] is not None: self._box.ymax = self.range[1] else: self._box.ymax = positive_vals and max( max(positive_vals), self.zero ) or self.zero
(self, positive_vals, negative_vals)
19,321
pygal.graph.stackedbar
_get_separated_values
Separate values between positives and negatives stacked
def _get_separated_values(self, secondary=False): """Separate values between positives and negatives stacked""" series = self.secondary_series if secondary else self.series transposed = list(zip(*[serie.values for serie in series])) positive_vals = [ sum([val for val in vals if val is not None and val >= self.zero]) for vals in transposed ] negative_vals = [ sum([val for val in vals if val is not None and val < self.zero]) for vals in transposed ] return positive_vals, negative_vals
(self, secondary=False)
19,330
pygal.graph.stackedbar
_plot
Draw bars for series and secondary series
def _plot(self): """Draw bars for series and secondary series""" for serie in self.series[::-1 if self.stack_from_top else 1]: self.bar(serie) for serie in self.secondary_series[::-1 if self.stack_from_top else 1]: self.bar(serie, True)
(self)
19,333
pygal.graph.stackedbar
_pre_compute_secondary
Compute secondary y min and max
def _pre_compute_secondary(self, positive_vals, negative_vals): """Compute secondary y min and max""" self._secondary_min = ( negative_vals and min(min(negative_vals), self.zero) ) or self.zero self._secondary_max = ( positive_vals and max(max(positive_vals), self.zero) ) or self.zero
(self, positive_vals, negative_vals)
19,365
pygal.graph.horizontalstackedline
HorizontalStackedLine
Horizontal Stacked Line graph
class HorizontalStackedLine(HorizontalGraph, StackedLine): """Horizontal Stacked Line graph""" def _plot(self): """Draw the lines in reverse order""" for serie in self.series[::-1]: self.line(serie) for serie in self.secondary_series[::-1]: self.line(serie, True)
(*args, **kwargs)
19,381
pygal.graph.stackedline
_fill
Add extra values to fill the line
def _fill(self, values): """Add extra values to fill the line""" if not self._previous_line: self._previous_line = values return super(StackedLine, self)._fill(values) new_values = values + list(reversed(self._previous_line)) self._previous_line = values return new_values
(self, values)
19,392
pygal.graph.stackedline
_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 series_group in (self.series, self.secondary_series): accumulation = [0] * self._len for serie in series_group[::-1 if self.stack_from_top else 1]: accumulation = list(map(sum, zip(accumulation, serie.values))) serie.points = [(x_pos[i], v) for i, v in enumerate(accumulation)] if serie.points and self.interpolate: serie.interpolated = self._interpolate(x_pos, accumulation) else: serie.interpolated = []
(self, x_pos)
19,401
pygal.graph.stackedline
_value_format
Display value and cumulation
def _value_format(self, value, serie, index): """ Display value and cumulation """ sum_ = serie.points[index][1] if serie in self.series and ( self.stack_from_top and self.series.index(serie) == self._order - 1 or not self.stack_from_top and self.series.index(serie) == 0): return super(StackedLine, self)._value_format(value) return '%s (+%s)' % (self._y_format(sum_), self._y_format(value))
(self, value, serie, index)
19,424
pygal.graph.line
Line
Line graph class
class Line(Graph): """Line graph class""" 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) @cached_property def _values(self): """Getter for series values (flattened)""" return [ val[1] for serie in self.series for val in (serie.interpolated if self.interpolate else serie.points) if val[1] is not None and (not self.logarithmic or val[1] > 0) ] @cached_property def _secondary_values(self): """Getter for secondary series values (flattened)""" return [ val[1] for serie in self.secondary_series for val in (serie.interpolated if self.interpolate else serie.points) if val[1] is not None and (not self.logarithmic or val[1] > 0) ] def _fill(self, values): """Add extra values to fill the line""" zero = self.view.y(min(max(self.zero, self._box.ymin), self._box.ymax)) # Check to see if the data has been padded with "none's" # Fill doesn't work correctly otherwise end = len(values) - 1 while end > 0: x, y = values[end] if self.missing_value_fill_truncation == "either": if x is not None and y is not None: break elif self.missing_value_fill_truncation == "x": if x is not None: break elif self.missing_value_fill_truncation == "y": if y is not None: break else: raise ValueError( "Invalid value ({}) for config key " "'missing_value_fill_truncation';" " Use 'x', 'y' or 'either'".format( self.missing_value_fill_truncation ) ) end -= 1 return ([(values[0][0], zero)] + values + [(values[end][0], zero)]) def line(self, serie, rescale=False): """Draw the line serie""" serie_node = self.svg.serie(serie) if rescale and self.secondary_series: points = self._rescale(serie.points) else: points = serie.points view_values = list(map(self.view, points)) if serie.show_dots: for i, (x, y) in enumerate(view_values): if None in (x, y): continue if self.logarithmic: if points[i][1] is None or points[i][1] <= 0: continue if (serie.show_only_major_dots and self.x_labels and i < len(self.x_labels) and self.x_labels[i] not in self._x_labels_major): continue metadata = serie.metadata.get(i) classes = [] if x > self.view.width / 2: classes.append('left') if y > self.view.height / 2: classes.append('top') classes = ' '.join(classes) self._confidence_interval( serie_node['overlay'], x, y, serie.values[i], metadata ) dots = decorate( self.svg, self.svg.node(serie_node['overlay'], class_="dots"), metadata ) val = self._format(serie, i) alter( self.svg.transposable_node( dots, 'circle', cx=x, cy=y, r=serie.dots_size, class_='dot reactive tooltip-trigger' ), metadata ) self._tooltip_data( dots, val, x, y, xlabel=self._get_x_label(i) ) self._static_value( serie_node, val, x + self.style.value_font_size, y + self.style.value_font_size, metadata ) if serie.stroke: if self.interpolate: points = serie.interpolated if rescale and self.secondary_series: points = self._rescale(points) view_values = list(map(self.view, points)) if serie.fill: view_values = self._fill(view_values) if serie.allow_interruptions: # view_values are in form [(x1, y1), (x2, y2)]. We # need to split that into multiple sequences if a # None is present here sequences = [] cur_sequence = [] for x, y in view_values: if y is None and len(cur_sequence) > 0: # emit current subsequence sequences.append(cur_sequence) cur_sequence = [] elif y is None: # just discard continue else: cur_sequence.append((x, y)) # append the element if len(cur_sequence) > 0: # emit last possible sequence sequences.append(cur_sequence) else: # plain vanilla rendering sequences = [view_values] if self.logarithmic: for seq in sequences: for ele in seq[::-1]: y = points[seq.index(ele)][1] if y is None or y <= 0: del seq[seq.index(ele)] for seq in sequences: self.svg.line( serie_node['plot'], seq, close=self._self_close, class_='line reactive' + (' nofill' if not serie.fill else '') ) def _compute(self): """Compute y min and max and y scale and set labels""" # X Labels if self.horizontal: self._x_pos = [ x / (self._len - 1) for x in range(self._len) ][::-1] if self._len != 1 else [.5] # Center if only one value else: self._x_pos = [ x / (self._len - 1) for x in range(self._len) ] if self._len != 1 else [.5] # Center if only one value self._points(self._x_pos) if self.include_x_axis: # Y Label self._box.ymin = min(self._min or 0, 0) self._box.ymax = max(self._max or 0, 0) else: self._box.ymin = self._min self._box.ymax = self._max def _plot(self): """Plot the serie lines and secondary serie lines""" for serie in self.series: self.line(serie) for serie in self.secondary_series: self.line(serie, True)
(*args, **kwargs)
19,483
pygal.graph.pie
Pie
Pie graph class
class Pie(Graph): """Pie graph class""" _adapters = [positive, none_to_zero] def slice(self, serie, start_angle, total): """Make a serie slice""" serie_node = self.svg.serie(serie) dual = self._len > 1 and not self._order == 1 slices = self.svg.node(serie_node['plot'], class_="slices") serie_angle = 0 original_start_angle = start_angle if self.half_pie: center = ((self.width - self.margin_box.x) / 2., (self.height - self.margin_box.y) / 1.25) else: center = ((self.width - self.margin_box.x) / 2., (self.height - self.margin_box.y) / 2.) radius = min(center) for i, val in enumerate(serie.values): perc = val / total if self.half_pie: angle = 2 * pi * perc / 2 else: angle = 2 * pi * perc serie_angle += angle val = self._format(serie, i) metadata = serie.metadata.get(i) slice_ = decorate( self.svg, self.svg.node(slices, class_="slice"), metadata ) if dual: small_radius = radius * .9 big_radius = radius else: big_radius = radius * .9 small_radius = radius * serie.inner_radius alter( self.svg.slice( serie_node, slice_, big_radius, small_radius, angle, start_angle, center, val, i, metadata ), metadata ) start_angle += angle if dual: val = self._serie_format(serie, sum(serie.values)) self.svg.slice( serie_node, self.svg.node(slices, class_="big_slice"), radius * .9, 0, serie_angle, original_start_angle, center, val, i, metadata ) return serie_angle def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): """Draw all the serie slices""" total = sum(map(sum, map(lambda x: x.values, self.series))) if total == 0: return if self.half_pie: current_angle = 3 * pi / 2 else: current_angle = 0 for index, serie in enumerate(self.series): angle = self.slice(serie, current_angle, total) current_angle += angle
(config=None, **kwargs)
19,508
pygal.graph.pie
_plot
Draw all the serie slices
def _plot(self): """Draw all the serie slices""" total = sum(map(sum, map(lambda x: x.values, self.series))) if total == 0: return if self.half_pie: current_angle = 3 * pi / 2 else: current_angle = 0 for index, serie in enumerate(self.series): angle = self.slice(serie, current_angle, total) current_angle += angle
(self)
19,539
pygal.graph.pie
slice
Make a serie slice
def slice(self, serie, start_angle, total): """Make a serie slice""" serie_node = self.svg.serie(serie) dual = self._len > 1 and not self._order == 1 slices = self.svg.node(serie_node['plot'], class_="slices") serie_angle = 0 original_start_angle = start_angle if self.half_pie: center = ((self.width - self.margin_box.x) / 2., (self.height - self.margin_box.y) / 1.25) else: center = ((self.width - self.margin_box.x) / 2., (self.height - self.margin_box.y) / 2.) radius = min(center) for i, val in enumerate(serie.values): perc = val / total if self.half_pie: angle = 2 * pi * perc / 2 else: angle = 2 * pi * perc serie_angle += angle val = self._format(serie, i) metadata = serie.metadata.get(i) slice_ = decorate( self.svg, self.svg.node(slices, class_="slice"), metadata ) if dual: small_radius = radius * .9 big_radius = radius else: big_radius = radius * .9 small_radius = radius * serie.inner_radius alter( self.svg.slice( serie_node, slice_, big_radius, small_radius, angle, start_angle, center, val, i, metadata ), metadata ) start_angle += angle if dual: val = self._serie_format(serie, sum(serie.values)) self.svg.slice( serie_node, self.svg.node(slices, class_="big_slice"), radius * .9, 0, serie_angle, original_start_angle, center, val, i, metadata ) return serie_angle
(self, serie, start_angle, total)
19,541
pygal
PluginImportFixer
Allow external map plugins to be imported from pygal.maps package. It is a ``sys.meta_path`` loader.
class PluginImportFixer(object): """ Allow external map plugins to be imported from pygal.maps package. It is a ``sys.meta_path`` loader. """ def find_module(self, fullname, path=None): """ Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module. """ if fullname.startswith('pygal.maps.') and hasattr( maps, fullname.split('.')[2]): return self return None def load_module(self, name): """ Load the ``pygal.maps.name`` module from the previously loaded plugin """ if name not in sys.modules: sys.modules[name] = getattr(maps, name.split('.')[2]) return sys.modules[name]
()
19,542
pygal
find_module
Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module.
def find_module(self, fullname, path=None): """ Tell if the module to load can be loaded by the load_module function, ie: if it is a ``pygal.maps.*`` module. """ if fullname.startswith('pygal.maps.') and hasattr( maps, fullname.split('.')[2]): return self return None
(self, fullname, path=None)
19,543
pygal
load_module
Load the ``pygal.maps.name`` module from the previously loaded plugin
def load_module(self, name): """ Load the ``pygal.maps.name`` module from the previously loaded plugin """ if name not in sys.modules: sys.modules[name] = getattr(maps, name.split('.')[2]) return sys.modules[name]
(self, name)
19,544
pygal.graph.pyramid
Pyramid
Horizontal Pyramid graph class like the one used by age pyramid
class Pyramid(HorizontalGraph, VerticalPyramid): """Horizontal Pyramid graph class like the one used by age pyramid"""
(*args, **kwargs)
19,550
pygal.graph.pyramid
_bar
Internal stacking bar drawing function
def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal stacking bar drawing function""" if serie.index % 2: y = -y return super(VerticalPyramid, self)._bar(serie, parent, x, y, i, zero, secondary)
(self, serie, parent, x, y, i, zero, secondary=False)
19,552
pygal.graph.pyramid
_compute_box
Compute Y min and max
def _compute_box(self, positive_vals, negative_vals): """Compute Y min and max""" max_ = max( max(positive_vals or [self.zero]), max(negative_vals or [self.zero]) ) if self.range and self.range[0] is not None: self._box.ymin = self.range[0] else: self._box.ymin = -max_ if self.range and self.range[1] is not None: self._box.ymax = self.range[1] else: self._box.ymax = max_
(self, positive_vals, negative_vals)
19,563
pygal.graph.pyramid
_get_separated_values
Separate values between odd and even series stacked
def _get_separated_values(self, secondary=False): """Separate values between odd and even series stacked""" series = self.secondary_series if secondary else self.series positive_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if index % 2 ] ) ) negative_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if not index % 2 ] ) ) return list(positive_vals), list(negative_vals)
(self, secondary=False)
19,575
pygal.graph.pyramid
_pre_compute_secondary
Compute secondary y min and max
def _pre_compute_secondary(self, positive_vals, negative_vals): """Compute secondary y min and max""" self._secondary_max = max(max(positive_vals), max(negative_vals)) self._secondary_min = -self._secondary_max
(self, positive_vals, negative_vals)
19,584
pygal.graph.pyramid
_value_format
Format value for dual value display.
def _value_format(self, value): """Format value for dual value display.""" return super(VerticalPyramid, self)._value_format(value and abs(value))
(self, value)
19,607
pygal.graph.radar
Radar
Rada graph class
class Radar(Line): """Rada graph class""" _adapters = [positive, none_to_zero] def __init__(self, *args, **kwargs): """Init custom vars""" self._rmax = None super(Radar, self).__init__(*args, **kwargs) def _fill(self, values): """Add extra values to fill the line""" return values @cached_property def _values(self): """Getter for series values (flattened)""" if self.interpolate: return [ val[0] for serie in self.series for val in serie.interpolated ] else: return super(Line, self)._values def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarLogView else: view_class = PolarView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box ) def _x_axis(self, draw_axes=True): """Override x axis to make it polar""" if not self._x_labels or not self.show_x_labels: return axis = self.svg.node( self.nodes['plot'], class_="axis x web%s" % (' always_show' if self.show_x_guides else '') ) format_ = lambda x: '%f %f' % x center = self.view((0, 0)) r = self._rmax # Can't simply determine truncation truncation = self.truncate_label or 25 for label, theta in self._x_labels: major = label in self._x_labels_major if not (self.show_minor_x_labels or major): continue guides = self.svg.node(axis, class_='guides') end = self.view((r, theta)) self.svg.node( guides, 'path', d='M%s L%s' % (format_(center), format_(end)), class_='%s%sline' % ('axis ' if label == "0" else '', 'major ' if major else '') ) r_txt = (1 - self._box.__class__.margin) * self._box.ymax pos_text = self.view((r_txt, theta)) text = self.svg.node( guides, 'text', x=pos_text[0], y=pos_text[1], class_='major' if major else '' ) text.text = truncate(label, truncation) if text.text != label: self.svg.node(guides, 'title').text = label else: self.svg.node( guides, 'title', ).text = self._x_format(theta) angle = -theta + pi / 2 if cos(angle) < 0: angle -= pi text.attrib['transform'] = 'rotate(%f %s)' % ( self.x_label_rotation or deg(angle), format_(pos_text) ) def _y_axis(self, draw_axes=True): """Override y axis to make it polar""" if not self._y_labels or not self.show_y_labels: return axis = self.svg.node(self.nodes['plot'], class_="axis y web") for label, r in reversed(self._y_labels): major = r 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 '') ) if self.show_y_guides: self.svg.line( guides, [self.view((r, theta)) for theta in self._x_pos], close=True, class_='%sguide line' % ('major ' if major else '') ) x, y = self.view((r, self._x_pos[0])) x -= 5 text = self.svg.node( guides, 'text', x=x, y=y, 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) self.svg.node( guides, 'title', ).text = self._y_format(r) def _compute(self): """Compute r min max and labels position""" delta = 2 * pi / self._len if self._len else 0 self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)] for serie in self.all_series: serie.points = [(v, self._x_pos[i]) for i, v in enumerate(serie.values)] if self.interpolate: extended_x_pos = ([.5 * pi - delta] + self._x_pos) extended_vals = (serie.values[-1:] + serie.values) serie.interpolated = list( map( tuple, map( reversed, self._interpolate(extended_x_pos, extended_vals) ) ) ) # x labels space self._box.margin *= 2 self._rmin = self.zero self._rmax = self._max or 1 self._box.set_polar_box(self._rmin, self._rmax) self._self_close = True def _compute_y_labels(self): y_pos = compute_scale( self._rmin, self._rmax, self.logarithmic, self.order_min, self.min_scale, self.max_scale / 2 ) 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]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self._rmin = min(self._rmin, min(cut(self._y_labels, 1))) self._rmax = max(self._rmax, max(cut(self._y_labels, 1))) self._box.set_polar_box(self._rmin, self._rmax) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos))
(*args, **kwargs)
19,610
pygal.graph.radar
__init__
Init custom vars
def __init__(self, *args, **kwargs): """Init custom vars""" self._rmax = None super(Radar, self).__init__(*args, **kwargs)
(self, *args, **kwargs)
19,613
pygal.graph.radar
_compute
Compute r min max and labels position
def _compute(self): """Compute r min max and labels position""" delta = 2 * pi / self._len if self._len else 0 self._x_pos = [.5 * pi + i * delta for i in range(self._len + 1)] for serie in self.all_series: serie.points = [(v, self._x_pos[i]) for i, v in enumerate(serie.values)] if self.interpolate: extended_x_pos = ([.5 * pi - delta] + self._x_pos) extended_vals = (serie.values[-1:] + serie.values) serie.interpolated = list( map( tuple, map( reversed, self._interpolate(extended_x_pos, extended_vals) ) ) ) # x labels space self._box.margin *= 2 self._rmin = self.zero self._rmax = self._max or 1 self._box.set_polar_box(self._rmin, self._rmax) self._self_close = True
(self)
19,618
pygal.graph.radar
_compute_y_labels
null
def _compute_y_labels(self): y_pos = compute_scale( self._rmin, self._rmax, self.logarithmic, self.order_min, self.min_scale, self.max_scale / 2 ) 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]) title = y_label else: pos = self._adapt(y_label) title = self._y_format(pos) self._y_labels.append((title, pos)) self._rmin = min(self._rmin, min(cut(self._y_labels, 1))) self._rmax = max(self._rmax, max(cut(self._y_labels, 1))) self._box.set_polar_box(self._rmin, self._rmax) else: self._y_labels = list(zip(map(self._y_format, y_pos), y_pos))
(self)
19,623
pygal.graph.radar
_fill
Add extra values to fill the line
def _fill(self, values): """Add extra values to fill the line""" return values
(self, values)
19,640
pygal.graph.radar
_set_view
Assign a view to current graph
def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarLogView else: view_class = PolarView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._box )
(self)
19,644
pygal.graph.radar
_x_axis
Override x axis to make it polar
def _x_axis(self, draw_axes=True): """Override x axis to make it polar""" if not self._x_labels or not self.show_x_labels: return axis = self.svg.node( self.nodes['plot'], class_="axis x web%s" % (' always_show' if self.show_x_guides else '') ) format_ = lambda x: '%f %f' % x center = self.view((0, 0)) r = self._rmax # Can't simply determine truncation truncation = self.truncate_label or 25 for label, theta in self._x_labels: major = label in self._x_labels_major if not (self.show_minor_x_labels or major): continue guides = self.svg.node(axis, class_='guides') end = self.view((r, theta)) self.svg.node( guides, 'path', d='M%s L%s' % (format_(center), format_(end)), class_='%s%sline' % ('axis ' if label == "0" else '', 'major ' if major else '') ) r_txt = (1 - self._box.__class__.margin) * self._box.ymax pos_text = self.view((r_txt, theta)) text = self.svg.node( guides, 'text', x=pos_text[0], y=pos_text[1], class_='major' if major else '' ) text.text = truncate(label, truncation) if text.text != label: self.svg.node(guides, 'title').text = label else: self.svg.node( guides, 'title', ).text = self._x_format(theta) angle = -theta + pi / 2 if cos(angle) < 0: angle -= pi text.attrib['transform'] = 'rotate(%f %s)' % ( self.x_label_rotation or deg(angle), format_(pos_text) )
(self, draw_axes=True)
19,646
pygal.graph.radar
_y_axis
Override y axis to make it polar
def _y_axis(self, draw_axes=True): """Override y axis to make it polar""" if not self._y_labels or not self.show_y_labels: return axis = self.svg.node(self.nodes['plot'], class_="axis y web") for label, r in reversed(self._y_labels): major = r 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 '') ) if self.show_y_guides: self.svg.line( guides, [self.view((r, theta)) for theta in self._x_pos], close=True, class_='%sguide line' % ('major ' if major else '') ) x, y = self.view((r, self._x_pos[0])) x -= 5 text = self.svg.node( guides, 'text', x=x, y=y, 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) self.svg.node( guides, 'title', ).text = self._y_format(r)
(self, draw_axes=True)
19,666
pygal.graph.solidgauge
SolidGauge
null
class SolidGauge(Graph): def gaugify(self, serie, squares, sq_dimensions, current_square): serie_node = self.svg.serie(serie) if self.half_pie: start_angle = 3 * pi / 2 center = ((current_square[1] * sq_dimensions[0]) - (sq_dimensions[0] / 2.), (current_square[0] * sq_dimensions[1]) - (sq_dimensions[1] / 4)) end_angle = pi / 2 else: start_angle = 0 center = ((current_square[1] * sq_dimensions[0]) - (sq_dimensions[0] / 2.), (current_square[0] * sq_dimensions[1]) - (sq_dimensions[1] / 2.)) end_angle = 2 * pi max_value = serie.metadata.get(0, {}).get('max_value', 100) radius = min([sq_dimensions[0] / 2, sq_dimensions[1] / 2]) * .9 small_radius = radius * serie.inner_radius self.svg.gauge_background( serie_node, start_angle, center, radius, small_radius, end_angle, self.half_pie, self._serie_format(serie, max_value) ) sum_ = 0 for i, value in enumerate(serie.values): if value is None: continue ratio = min(value, max_value) / max_value if self.half_pie: angle = 2 * pi * ratio / 2 else: angle = 2 * pi * ratio val = self._format(serie, i) metadata = serie.metadata.get(i) gauge_ = decorate( self.svg, self.svg.node(serie_node['plot'], class_="gauge"), metadata ) alter( self.svg.solid_gauge( serie_node, gauge_, radius, small_radius, angle, start_angle, center, val, i, metadata, self.half_pie, end_angle, self._serie_format(serie, max_value) ), metadata ) start_angle += angle sum_ += value x, y = center self.svg.node( serie_node['text_overlay'], 'text', class_='value gauge-sum', x=x, y=y + self.style.value_font_size / 3, attrib={ 'text-anchor': 'middle' } ).text = self._serie_format(serie, sum_) def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): """Draw all the serie slices""" squares = self._squares() sq_dimensions = self.add_squares(squares) for index, serie in enumerate(self.series): current_square = self._current_square(squares, index) self.gaugify(serie, squares, sq_dimensions, current_square) def _squares(self): n_series_ = len(self.series) i = 2 if sqrt(n_series_).is_integer(): _x = int(sqrt(n_series_)) _y = int(sqrt(n_series_)) else: while i * i < n_series_: while n_series_ % i == 0: n_series_ = n_series_ / i i = i + 1 _y = int(n_series_) _x = int(len(self.series) / _y) if len(self.series) == 5: _x, _y = 2, 3 if abs(_x - _y) > 2: _sq = 3 while (_x * _y) - 1 < len(self.series): _x, _y = _sq, _sq _sq += 1 return (_x, _y) def _current_square(self, squares, index): current_square = [1, 1] steps = index + 1 steps_taken = 0 for i in range(squares[0] * squares[1]): steps_taken += 1 if steps_taken != steps and steps_taken % squares[0] != 0: current_square[1] += 1 elif steps_taken != steps and steps_taken % squares[0] == 0: current_square[1] = 1 current_square[0] += 1 else: return tuple(current_square) raise Exception( 'Something went wrong with the current square assignment.' )
(config=None, **kwargs)
19,680
pygal.graph.solidgauge
_current_square
null
def _current_square(self, squares, index): current_square = [1, 1] steps = index + 1 steps_taken = 0 for i in range(squares[0] * squares[1]): steps_taken += 1 if steps_taken != steps and steps_taken % squares[0] != 0: current_square[1] += 1 elif steps_taken != steps and steps_taken % squares[0] == 0: current_square[1] = 1 current_square[0] += 1 else: return tuple(current_square) raise Exception( 'Something went wrong with the current square assignment.' )
(self, squares, index)
19,692
pygal.graph.solidgauge
_plot
Draw all the serie slices
def _plot(self): """Draw all the serie slices""" squares = self._squares() sq_dimensions = self.add_squares(squares) for index, serie in enumerate(self.series): current_square = self._current_square(squares, index) self.gaugify(serie, squares, sq_dimensions, current_square)
(self)
19,700
pygal.graph.solidgauge
_squares
null
def _squares(self): n_series_ = len(self.series) i = 2 if sqrt(n_series_).is_integer(): _x = int(sqrt(n_series_)) _y = int(sqrt(n_series_)) else: while i * i < n_series_: while n_series_ % i == 0: n_series_ = n_series_ / i i = i + 1 _y = int(n_series_) _x = int(len(self.series) / _y) if len(self.series) == 5: _x, _y = 2, 3 if abs(_x - _y) > 2: _sq = 3 while (_x * _y) - 1 < len(self.series): _x, _y = _sq, _sq _sq += 1 return (_x, _y)
(self)
19,710
pygal.graph.solidgauge
gaugify
null
def gaugify(self, serie, squares, sq_dimensions, current_square): serie_node = self.svg.serie(serie) if self.half_pie: start_angle = 3 * pi / 2 center = ((current_square[1] * sq_dimensions[0]) - (sq_dimensions[0] / 2.), (current_square[0] * sq_dimensions[1]) - (sq_dimensions[1] / 4)) end_angle = pi / 2 else: start_angle = 0 center = ((current_square[1] * sq_dimensions[0]) - (sq_dimensions[0] / 2.), (current_square[0] * sq_dimensions[1]) - (sq_dimensions[1] / 2.)) end_angle = 2 * pi max_value = serie.metadata.get(0, {}).get('max_value', 100) radius = min([sq_dimensions[0] / 2, sq_dimensions[1] / 2]) * .9 small_radius = radius * serie.inner_radius self.svg.gauge_background( serie_node, start_angle, center, radius, small_radius, end_angle, self.half_pie, self._serie_format(serie, max_value) ) sum_ = 0 for i, value in enumerate(serie.values): if value is None: continue ratio = min(value, max_value) / max_value if self.half_pie: angle = 2 * pi * ratio / 2 else: angle = 2 * pi * ratio val = self._format(serie, i) metadata = serie.metadata.get(i) gauge_ = decorate( self.svg, self.svg.node(serie_node['plot'], class_="gauge"), metadata ) alter( self.svg.solid_gauge( serie_node, gauge_, radius, small_radius, angle, start_angle, center, val, i, metadata, self.half_pie, end_angle, self._serie_format(serie, max_value) ), metadata ) start_angle += angle sum_ += value x, y = center self.svg.node( serie_node['text_overlay'], 'text', class_='value gauge-sum', x=x, y=y + self.style.value_font_size / 3, attrib={ 'text-anchor': 'middle' } ).text = self._serie_format(serie, sum_)
(self, serie, squares, sq_dimensions, current_square)
19,726
pygal.graph.stackedbar
StackedBar
Stacked Bar graph class
class StackedBar(Bar): """Stacked Bar graph class""" _adapters = [none_to_zero] def _get_separated_values(self, secondary=False): """Separate values between positives and negatives stacked""" series = self.secondary_series if secondary else self.series transposed = list(zip(*[serie.values for serie in series])) positive_vals = [ sum([val for val in vals if val is not None and val >= self.zero]) for vals in transposed ] negative_vals = [ sum([val for val in vals if val is not None and val < self.zero]) for vals in transposed ] return positive_vals, negative_vals def _compute_box(self, positive_vals, negative_vals): """Compute Y min and max""" if self.range and self.range[0] is not None: self._box.ymin = self.range[0] else: self._box.ymin = negative_vals and min( min(negative_vals), self.zero ) or self.zero if self.range and self.range[1] is not None: self._box.ymax = self.range[1] else: self._box.ymax = positive_vals and max( max(positive_vals), self.zero ) or self.zero def _compute(self): """Compute y min and max and y scale and set labels""" positive_vals, negative_vals = self._get_separated_values() if self.logarithmic: positive_vals = list( filter(lambda x: x > self.zero, positive_vals) ) negative_vals = list( filter(lambda x: x > self.zero, negative_vals) ) self._compute_box(positive_vals, negative_vals) positive_vals = positive_vals or [self.zero] negative_vals = negative_vals or [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.negative_cumulation = [0] * self._len self.positive_cumulation = [0] * self._len if self.secondary_series: positive_vals, negative_vals = self._get_separated_values(True) positive_vals = positive_vals or [self.zero] negative_vals = negative_vals or [self.zero] self.secondary_negative_cumulation = [0] * self._len self.secondary_positive_cumulation = [0] * self._len self._pre_compute_secondary(positive_vals, negative_vals) self._x_pos = [(i + .5) / self._len for i in range(self._len)] def _pre_compute_secondary(self, positive_vals, negative_vals): """Compute secondary y min and max""" self._secondary_min = ( negative_vals and min(min(negative_vals), self.zero) ) or self.zero self._secondary_max = ( positive_vals and max(max(positive_vals), self.zero) ) or self.zero def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal stacking bar drawing function""" if secondary: cumulation = ( self.secondary_negative_cumulation if y < self.zero else self.secondary_positive_cumulation ) else: cumulation = ( self.negative_cumulation if y < self.zero else self.positive_cumulation ) zero = cumulation[i] cumulation[i] = zero + y if zero == 0: zero = self.zero y -= self.zero y += zero width = (self.view.x(1) - self.view.x(0)) / self._len x, y = self.view((x, y)) y = y or 0 series_margin = width * self._series_margin x += series_margin width -= 2 * series_margin if self.secondary_series: width /= 2 x += int(secondary) * 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 self.svg.transposable_node( parent, 'rect', x=x, y=y, rx=r, ry=r, width=width, height=height, class_='rect reactive tooltip-trigger' ) return x, y, width, height def _plot(self): """Draw bars for series and secondary series""" for serie in self.series[::-1 if self.stack_from_top else 1]: self.bar(serie) for serie in self.secondary_series[::-1 if self.stack_from_top else 1]: self.bar(serie, True)
(config=None, **kwargs)
19,789
pygal.graph.stackedline
StackedLine
Stacked Line graph class
class StackedLine(Line): """Stacked Line graph class""" _adapters = [none_to_zero] def __init__(self, *args, **kwargs): """Custom variable initialization""" self._previous_line = None super(StackedLine, self).__init__(*args, **kwargs) def _value_format(self, value, serie, index): """ Display value and cumulation """ sum_ = serie.points[index][1] if serie in self.series and ( self.stack_from_top and self.series.index(serie) == self._order - 1 or not self.stack_from_top and self.series.index(serie) == 0): return super(StackedLine, self)._value_format(value) return '%s (+%s)' % (self._y_format(sum_), self._y_format(value)) def _fill(self, values): """Add extra values to fill the line""" if not self._previous_line: self._previous_line = values return super(StackedLine, self)._fill(values) new_values = values + list(reversed(self._previous_line)) self._previous_line = values return new_values def _points(self, x_pos): """ Convert given data values into drawable points (x, y) and interpolated points if interpolate option is specified """ for series_group in (self.series, self.secondary_series): accumulation = [0] * self._len for serie in series_group[::-1 if self.stack_from_top else 1]: accumulation = list(map(sum, zip(accumulation, serie.values))) serie.points = [(x_pos[i], v) for i, v in enumerate(accumulation)] if serie.points and self.interpolate: serie.interpolated = self._interpolate(x_pos, accumulation) else: serie.interpolated = [] def _plot(self): """Plot stacked serie lines and stacked secondary lines""" for serie in self.series[::-1 if self.stack_from_top else 1]: self.line(serie) for serie in self.secondary_series[::-1 if self.stack_from_top else 1]: self.line(serie, True)
(*args, **kwargs)
19,792
pygal.graph.stackedline
__init__
Custom variable initialization
def __init__(self, *args, **kwargs): """Custom variable initialization""" self._previous_line = None super(StackedLine, self).__init__(*args, **kwargs)
(self, *args, **kwargs)
19,815
pygal.graph.stackedline
_plot
Plot stacked serie lines and stacked secondary lines
def _plot(self): """Plot stacked serie lines and stacked secondary lines""" for serie in self.series[::-1 if self.stack_from_top else 1]: self.line(serie) for serie in self.secondary_series[::-1 if self.stack_from_top else 1]: self.line(serie, True)
(self)
19,848
pygal.graph.time
TimeDeltaLine
TimeDelta abscissa xy graph class
class TimeDeltaLine(XY): """TimeDelta abscissa xy graph class""" _x_adapters = [timedelta_to_seconds] @property def _x_format(self): """Return the value formatter for this graph""" def timedelta_to_str(x): td = timedelta(seconds=x) return self.x_value_formatter(td) return timedelta_to_str
(*args, **kwargs)
19,907
pygal.graph.time
TimeLine
Time abscissa xy graph class
class TimeLine(DateTimeLine): """Time abscissa xy graph class""" _x_adapters = [positive, time_to_seconds, datetime_to_time] @property def _x_format(self): """Return the value formatter for this graph""" def date_to_str(x): t = seconds_to_time(x) return self.x_value_formatter(t) return date_to_str
(*args, **kwargs)
19,966
pygal.graph.treemap
Treemap
Treemap graph class
class Treemap(Graph): """Treemap graph class""" _adapters = [positive, none_to_zero] def _rect(self, serie, serie_node, rects, val, x, y, w, h, i): rx, ry = self.view((x, y)) rw, rh = self.view((x + w, y + h)) rw -= rx rh -= ry metadata = serie.metadata.get(i) val = self._format(serie, i) rect = decorate( self.svg, self.svg.node(rects, class_="rect"), metadata ) alter( self.svg.node( rect, 'rect', x=rx, y=ry, width=rw, height=rh, class_='rect reactive tooltip-trigger' ), metadata ) self._tooltip_data( rect, val, rx + rw / 2, ry + rh / 2, 'centered', self._get_x_label(i) ) self._static_value(serie_node, val, rx + rw / 2, ry + rh / 2, metadata) def _binary_tree(self, data, total, x, y, w, h, parent=None): if total == 0: return if len(data) == 1: if parent: i, datum = data[0] serie, serie_node, rects = parent self._rect(serie, serie_node, rects, datum, x, y, w, h, i) else: datum = data[0] serie_node = self.svg.serie(datum) self._binary_tree( list(enumerate(datum.values)), total, x, y, w, h, ( datum, serie_node, self.svg.node(serie_node['plot'], class_="rects") ) ) return midpoint = total / 2 pivot_index = 1 running_sum = 0 for i, elt in enumerate(data): if running_sum >= midpoint: pivot_index = i break running_sum += elt[1] if parent else sum(elt.values) half1 = data[:pivot_index] half2 = data[pivot_index:] if parent: half1_sum = sum(cut(half1, 1)) half2_sum = sum(cut(half2, 1)) else: half1_sum = sum(map(sum, map(lambda x: x.values, half1))) half2_sum = sum(map(sum, map(lambda x: x.values, half2))) pivot_pct = half1_sum / total if h > w: y_pivot = pivot_pct * h self._binary_tree(half1, half1_sum, x, y, w, y_pivot, parent) self._binary_tree( half2, half2_sum, x, y + y_pivot, w, h - y_pivot, parent ) else: x_pivot = pivot_pct * w self._binary_tree(half1, half1_sum, x, y, x_pivot, h, parent) self._binary_tree( half2, half2_sum, x + x_pivot, y, w - x_pivot, h, parent ) def _compute_x_labels(self): pass def _compute_y_labels(self): pass def _plot(self): total = sum(map(sum, map(lambda x: x.values, self.series))) if total == 0: return gw = self.width - self.margin_box.x gh = self.height - self.margin_box.y self.view.box.xmin = self.view.box.ymin = x = y = 0 self.view.box.xmax = w = (total * gw / gh)**.5 self.view.box.ymax = h = total / w self.view.box.fix() self._binary_tree(self.series, total, x, y, w, h)
(config=None, **kwargs)
19,972
pygal.graph.treemap
_binary_tree
null
def _binary_tree(self, data, total, x, y, w, h, parent=None): if total == 0: return if len(data) == 1: if parent: i, datum = data[0] serie, serie_node, rects = parent self._rect(serie, serie_node, rects, datum, x, y, w, h, i) else: datum = data[0] serie_node = self.svg.serie(datum) self._binary_tree( list(enumerate(datum.values)), total, x, y, w, h, ( datum, serie_node, self.svg.node(serie_node['plot'], class_="rects") ) ) return midpoint = total / 2 pivot_index = 1 running_sum = 0 for i, elt in enumerate(data): if running_sum >= midpoint: pivot_index = i break running_sum += elt[1] if parent else sum(elt.values) half1 = data[:pivot_index] half2 = data[pivot_index:] if parent: half1_sum = sum(cut(half1, 1)) half2_sum = sum(cut(half2, 1)) else: half1_sum = sum(map(sum, map(lambda x: x.values, half1))) half2_sum = sum(map(sum, map(lambda x: x.values, half2))) pivot_pct = half1_sum / total if h > w: y_pivot = pivot_pct * h self._binary_tree(half1, half1_sum, x, y, w, y_pivot, parent) self._binary_tree( half2, half2_sum, x, y + y_pivot, w, h - y_pivot, parent ) else: x_pivot = pivot_pct * w self._binary_tree(half1, half1_sum, x, y, x_pivot, h, parent) self._binary_tree( half2, half2_sum, x + x_pivot, y, w - x_pivot, h, parent )
(self, data, total, x, y, w, h, parent=None)
19,992
pygal.graph.treemap
_plot
null
def _plot(self): total = sum(map(sum, map(lambda x: x.values, self.series))) if total == 0: return gw = self.width - self.margin_box.x gh = self.height - self.margin_box.y self.view.box.xmin = self.view.box.ymin = x = y = 0 self.view.box.xmax = w = (total * gw / gh)**.5 self.view.box.ymax = h = total / w self.view.box.fix() self._binary_tree(self.series, total, x, y, w, h)
(self)
19,995
pygal.graph.treemap
_rect
null
def _rect(self, serie, serie_node, rects, val, x, y, w, h, i): rx, ry = self.view((x, y)) rw, rh = self.view((x + w, y + h)) rw -= rx rh -= ry metadata = serie.metadata.get(i) val = self._format(serie, i) rect = decorate( self.svg, self.svg.node(rects, class_="rect"), metadata ) alter( self.svg.node( rect, 'rect', x=rx, y=ry, width=rw, height=rh, class_='rect reactive tooltip-trigger' ), metadata ) self._tooltip_data( rect, val, rx + rw / 2, ry + rh / 2, 'centered', self._get_x_label(i) ) self._static_value(serie_node, val, rx + rw / 2, ry + rh / 2, metadata)
(self, serie, serie_node, rects, val, x, y, w, h, i)
20,025
pygal.graph.pyramid
VerticalPyramid
Vertical Pyramid graph class
class VerticalPyramid(StackedBar): """Vertical Pyramid graph class""" _adapters = [positive] def _value_format(self, value): """Format value for dual value display.""" return super(VerticalPyramid, self)._value_format(value and abs(value)) def _get_separated_values(self, secondary=False): """Separate values between odd and even series stacked""" series = self.secondary_series if secondary else self.series positive_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if index % 2 ] ) ) negative_vals = map( sum, zip( *[ serie.safe_values for index, serie in enumerate(series) if not index % 2 ] ) ) return list(positive_vals), list(negative_vals) def _compute_box(self, positive_vals, negative_vals): """Compute Y min and max""" max_ = max( max(positive_vals or [self.zero]), max(negative_vals or [self.zero]) ) if self.range and self.range[0] is not None: self._box.ymin = self.range[0] else: self._box.ymin = -max_ if self.range and self.range[1] is not None: self._box.ymax = self.range[1] else: self._box.ymax = max_ def _pre_compute_secondary(self, positive_vals, negative_vals): """Compute secondary y min and max""" self._secondary_max = max(max(positive_vals), max(negative_vals)) self._secondary_min = -self._secondary_max def _bar(self, serie, parent, x, y, i, zero, secondary=False): """Internal stacking bar drawing function""" if serie.index % 2: y = -y return super(VerticalPyramid, self)._bar(serie, parent, x, y, i, zero, secondary)
(config=None, **kwargs)
20,088
pygal.graph.xy
XY
XY Line graph class
class XY(Line, Dual): """XY Line graph class""" _x_adapters = [] @cached_property def xvals(self): """All x values""" return [ val[0] for serie in self.all_series for val in serie.values if val[0] is not None ] @cached_property def yvals(self): """All y values""" return [ val[1] for serie in self.series for val in serie.values if val[1] is not None ] @cached_property def _min(self): """Getter for the minimum series value""" return ( self.range[0] if (self.range and self.range[0] is not None) else (min(self.yvals) if self.yvals else None) ) @cached_property def _max(self): """Getter for the maximum series value""" return ( self.range[1] if (self.range and self.range[1] is not None) else (max(self.yvals) if self.yvals else None) ) 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
(*args, **kwargs)
20,152
importlib_metadata
entry_points
Return EntryPoint objects for all installed packages. Pass selection parameters (group or name) to filter the result to entry points matching those properties (see EntryPoints.select()). :return: EntryPoints for all installed packages.
def entry_points(**params) -> EntryPoints: """Return EntryPoint objects for all installed packages. Pass selection parameters (group or name) to filter the result to entry points matching those properties (see EntryPoints.select()). :return: EntryPoints for all installed packages. """ eps = itertools.chain.from_iterable( dist.entry_points for dist in _unique(distributions()) ) return EntryPoints(eps).select(**params)
(**params) -> importlib_metadata.EntryPoints
20,168
gitcomp.ser_de
FIELD
An enumeration.
class FIELD(Enum): user_data = User repo_data = Repository
(value, names=None, *, module=None, qualname=None, type=None, start=1)
20,169
gitcomp.gitcomp_core
GitComp
null
class GitComp: users: List[str] repos: List[str] user_data: Dict[str, User] = None repo_data: Dict[str, Repository] = None __username_regex = r'^[a-zA-Z0-9]+' __repo_regex = r'^[A-Za-z0-9]+/[A-Za-z0-9]+' def __init__(self, users: List[str] = None, repos: List[str] = None): self.users = users self.repos = repos self.user_data = {} if self.users is not None: self.user_data = {} self.__fetch_user_data() if self.repos is not None: self.repo_data = {} self.__fetch_repo_data() def __fetch_user_data(self): self.__validate_user_names() response = NetMod().fetch_users_data(self.users) for user in response: self.user_data[user] = User(response[user]) def __validate_user_names(self): for user in self.users: if not re.match(GitComp.__username_regex, user): raise ValueError(f""" Improper username {user} """) def __fetch_repo_data(self): self.__validate_repo_string() response = NetMod().fetch_repos_data(self.repos) for repo in response: self.repo_data[repo] = Repository(response[repo]) def __validate_repo_string(self): for repo in self.repos: if not re.match(GitComp.__repo_regex, repo): raise ValueError(""" Improper repository format. Provide the repository name as: <user-name>/<repository-name> """)
(users: List[str] = None, repos: List[str] = None)
20,170
gitcomp.gitcomp_core
__fetch_repo_data
null
def __fetch_repo_data(self): self.__validate_repo_string() response = NetMod().fetch_repos_data(self.repos) for repo in response: self.repo_data[repo] = Repository(response[repo])
(self)
20,171
gitcomp.gitcomp_core
__fetch_user_data
null
def __fetch_user_data(self): self.__validate_user_names() response = NetMod().fetch_users_data(self.users) for user in response: self.user_data[user] = User(response[user])
(self)
20,172
gitcomp.gitcomp_core
__validate_repo_string
null
def __validate_repo_string(self): for repo in self.repos: if not re.match(GitComp.__repo_regex, repo): raise ValueError(""" Improper repository format. Provide the repository name as: <user-name>/<repository-name> """)
(self)
20,173
gitcomp.gitcomp_core
__validate_user_names
null
def __validate_user_names(self): for user in self.users: if not re.match(GitComp.__username_regex, user): raise ValueError(f""" Improper username {user} """)
(self)
20,174
gitcomp.gitcomp_core
__init__
null
def __init__(self, users: List[str] = None, repos: List[str] = None): self.users = users self.repos = repos self.user_data = {} if self.users is not None: self.user_data = {} self.__fetch_user_data() if self.repos is not None: self.repo_data = {} self.__fetch_repo_data()
(self, users: Optional[List[str]] = None, repos: Optional[List[str]] = None)
20,175
gitcomp.ser_de
PROP
An enumeration.
class PROP(Enum): users = 'user_data' repos = 'repo_data'
(value, names=None, *, module=None, qualname=None, type=None, start=1)