Beispiel #1
0
    def test_new_line_point_overlap(self):
        """
        Test that when creating a new line with points, the lines do not overlap.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        for label in string.ascii_uppercase:
            point, annotation = viz.legend.draw_point(label)
        self.assertGreaterEqual(len(viz.legend.lines), 2)

        axes = viz.axes
        figure = viz.figure
        """
        Compare the top annotation with the one beneath it.
        """
        for i in range(len(viz.legend.lines) - 1):
            top = viz.legend.lines[i][0][1]
            bottom = viz.legend.lines[i + 1][0][1]
            self.assertLessEqual(round(bottom.get_virtual_bb().y1, 10),
                                 round(top.get_virtual_bb().y0, 10))

            top = viz.legend.lines[i][0][0]
            bottom = viz.legend.lines[i + 1][0][0]
            bb_top = util.get_bb(figure, axes, top)
            bb_bottom = util.get_bb(figure, axes, bottom)
            self.assertLessEqual(round(bb_bottom.y1, 10), round(bb_top.y0, 10))
Beispiel #2
0
    def test_draw_fits_within_height(self):
        """
        Test that the points fit within the given height.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        height = 0.5
        lim = (0.25, 0.75)
        drawn = viz.draw_population(15, 3, '', height=height)

        # test that all points are within the height
        points = [point for column in drawn for point in column]
        for point in points:
            bb = util.get_bb(viz.figure, viz.axes, point)
            self.assertTrue(lim[0] <= (bb.y0 + bb.y1) / 2. <= lim[1])

        # test that the first point in each column is at the lowest point
        for column in drawn:
            bb = util.get_bb(viz.figure, viz.axes, column[0])
            self.assertEqual(lim[0], (bb.y0 + bb.y1) / 2)

        # test that the last point in each column is at the highest point
        for column in drawn:
            bb = util.get_bb(viz.figure, viz.axes, column[-1])
            self.assertEqual(lim[1], (bb.y0 + bb.y1) / 2)
Beispiel #3
0
    def _newline(self, visual, annotation, linespacing, va='bottom'):
        """
		Create a new line with the given legend.

		:param visual: The visual of the legend.
		:type visual: object
		:param annotation: The drawn annotation.
		:type annotation: :class:`~text.annotation.Annotation`
		:param linespacing: The space between lines.
		:type linespacing: float
		:param va: The vertical alignment, can be one of `top`, `center` or `bottom`.
				   If the vertical alignment is `top`, the given y-coordinate becomes the highest point of the annotation.
				   If the vertical alignment is `center`, the given y-coordinate becomes the center point of the annotation.
				   If the vertical alignment is `bottom`, the given y-coordinate becomes the lowest point of the annotation.
		:type va: str
		"""

        figure = self.drawable.figure
        axis = self.drawable.axis
        """
		Go through each line and move all of its components one line up.
		"""
        for line in self.lines:
            for push_visual, push_annotation in line:
                """
				The lines can be pushed up by the height of the line.
				"""
                bb = util.get_bb(figure,
                                 axis,
                                 push_visual,
                                 transform=axis.transAxes)
                push_visual.set_ydata([bb.y0 + linespacing] * 2)
                """
				The annotations are moved differently depending on the vertical alignment.
				If the vertical alignment is `top`, the annotation is moved from the top.
				If the vertical alignment is `center`, the annotation is moved from the center.
				If the vertical alignment is `bottom`, the annotation is moved from the bottom.
				"""
                bb = push_annotation.get_virtual_bb(transform=axis.transAxes)
                if va == 'top':
                    y = bb.y1
                elif va == 'center':
                    y = (bb.y0 + bb.y1) / 2.
                elif va == 'bottom':
                    y = bb.y0

                push_annotation.set_position((bb.x0, y + linespacing),
                                             va=va,
                                             transform=axis.transAxes)
        """
		Move the visual and the annotation to the start of the line.
		Finally, create a new line container.
		"""
        visualbb = util.get_bb(figure, axis, visual, transform=axis.transAxes)
        visual.set_xdata([0, 0.025])
        annotationbb = annotation.get_virtual_bb(transform=axis.transAxes)
        annotation.set_position((visualbb.width + 0.00625, 1),
                                va=va,
                                transform=axis.transAxes)
        self.lines.append([(visual, annotation)])
Beispiel #4
0
    def test_fit_axes_secondary_labels(self):
        """
        Test that when there is a secondary axes, the y-ticks are taken from it.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        viz.axes.spines['left'].set_position(('data', 0))
        viz.axes.spines['right'].set_position(('data', 1))
        viz.set_yticks([ ])
        viz.secondary = viz.twinx()
        viz.secondary.tick_params(labelleft=True, labelright=True)
        viz.secondary.spines['left'].set_position(('data', 0))
        viz.secondary.spines['right'].set_position(('data', 1))
        dummy = DummyVisualization(viz)

        # set the y-ticks
        viz.secondary.set_yticks(range(0, 10))
        viz.secondary.set_yticklabels([ f"label { i }" for i in range(0, 10) ])
        self.assertEqual(0, len(viz.get_yticklabels())) # no ticks in the primary axes
        labels = viz.secondary.get_yticklabels()
        self.assertEqual(20, len(labels)) # on both sides

        # make sure that the x-limit moves to the right
        xlim = viz.secondary.get_xlim()
        dummy._fit_axes()
        self.assertGreater(xlim[0], viz.secondary.get_xlim()[0])
        self.assertLess(xlim[1], viz.secondary.get_xlim()[1])
        llimit = min(util.get_bb(viz.figure, viz.axes, label).x0 for label in labels)
        rlimit = max(util.get_bb(viz.figure, viz.axes, label).x1 for label in labels)
        self.assertEqual(round(llimit, 10), round(viz.get_xlim()[0], 10))
        self.assertEqual(round(rlimit, 10), round(viz.get_xlim()[1], 10))
Beispiel #5
0
    def test_redraw_move_all(self):
        """
        Test that when the x-axis label is at the top, the legend moves the visuals up as well.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 5)))
        figure, axes = viz.figure, viz.axes
        viz.legend.draw_line('label')
        legend_bb = viz.legend.get_virtual_bb(transform=axes.transAxes)
        """
        Move the x-axis label and ticks to the top.
        """
        viz.axes.xaxis.set_label_position('top')
        viz.axes.xaxis.tick_top()
        viz.axes.spines['top'].set_visible(True)
        viz.axes.spines['bottom'].set_visible(False)
        """
        After adding a label, the legend should move up.
        """
        viz.set_xlabel('label')
        visual, annotation = viz.legend.lines[0][0]
        before_annotation = annotation.get_virtual_bb(transform=axes.transAxes)
        before_visual = util.get_bb(figure,
                                    axes,
                                    visual,
                                    transform=axes.transAxes)
        viz.legend.redraw()
        after_annotation = annotation.get_virtual_bb(transform=axes.transAxes)
        after_visual = util.get_bb(figure,
                                   axes,
                                   visual,
                                   transform=axes.transAxes)
        self.assertLess(before_annotation.y0, after_annotation.y0)
        self.assertLess(before_visual.y0, after_visual.y0)
Beispiel #6
0
    def test_fit_axes_wider(self):
        """
        Test that when the axes are wider than the ticks, fitting the axes changes nothing.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        viz.axes.spines['left'].set_position(('data', 0))
        viz.axes.spines['right'].set_position(('data', 1))
        viz.tick_params(labelright=True)
        dummy = DummyVisualization(viz)

        # set the y-ticks
        viz.set_yticks(range(0, 10))
        viz.set_yticklabels([ f"label { i }" for i in range(0, 10) ])
        labels = viz.get_yticklabels()
        self.assertEqual(20, len(labels)) # on both sides
        llimit = min(util.get_bb(viz.figure, viz.axes, label).x0 for label in labels)
        rlimit = max(util.get_bb(viz.figure, viz.axes, label).x1 for label in labels)

        # position the axes
        viz.axes.spines['left'].set_position(('data', 0))
        viz.axes.spines['right'].set_position(('data', 0))
        viz.set_xlim((-100, 100))

        # make sure that the x-limit does not move after fitting it
        xlim = viz.get_xlim()
        self.assertLess(xlim[0], llimit)
        self.assertGreater(xlim[1], rlimit)
        dummy._fit_axes()
        self.assertEqual(xlim, viz.get_xlim())
Beispiel #7
0
	def _tighten(self, drawn_lines):
		"""
		Move the text visualization so that it starts from x- and y-coordinate 0.

		:param drawn_lines: A list of drawn lines.
						   The function expects lines to be tuples.
						   The first value of each tuple should be the legend labels.
						   The second value of each tuple should be the tokens.
		:type drawn_lines: list of float
		"""

		figure = self.drawable.figure
		axis = self.drawable.axis

		"""
		Calculate the necessary offset.
		"""
		x_offset, y_offset = 0, 0
		for (labels, tokens) in drawn_lines:
			for label in labels:
				bb = util.get_bb(figure, axis, label)
				x_offset = min(x_offset, bb.x0)
				y_offset = min(y_offset, bb.y0)

		"""
		Move all labels and tokens by this offset.
		"""
		for (labels, tokens) in drawn_lines:
			for token in labels + tokens:
				bb = util.get_bb(figure, axis, token)
				token.set_position((bb.x0 - x_offset, bb.y0 - y_offset))
Beispiel #8
0
    def test_draw_override_pad(self):
        """
		Test that when drawing bars, padding can be overriden through the style.
		"""

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        bar = Bar100(viz)
        values = [{
            'value': 10
        }, {
            'value': 10,
            'style': {}
        }, {
            'value': 10,
            'style': {
                'pad': 0
            }
        }, {
            'value': 10
        }]
        bars = bar.draw(values, 'label', pad=1)
        self.assertEqual(
            24, round(util.get_bb(viz.figure, viz.axes, bars[1]).width, 10))
        self.assertEqual(
            25, round(util.get_bb(viz.figure, viz.axes, bars[2]).width, 10))
Beispiel #9
0
    def test_get_radius_unequal_data_ratio(self):
        """
		Test that when getting the radius, the correct radii are used even if the data ratio is not equal.
		"""

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))

        graph = Graph(viz)
        point = viz.scatter(0, 0, s=1000)
        viz.set_xlim((-2, 2))
        viz.set_ylim((-1, 1))

        bb = util.get_bb(viz.figure, viz.axes, point)
        self.assertEqual(round(bb.width / 2, 10),
                         round(graph._get_radius(point, s=1000)[0], 10))
        self.assertEqual(round(bb.height / 2, 10),
                         round(graph._get_radius(point, s=1000)[1], 10))

        viz.set_xlim((-1, 1))
        viz.set_ylim((-2, 2))

        bb = util.get_bb(viz.figure, viz.axes, point)
        self.assertEqual(round(bb.width / 2, 10),
                         round(graph._get_radius(point, s=1000)[0], 10))
        self.assertEqual(round(bb.height / 2, 10),
                         round(graph._get_radius(point, s=1000)[1], 10))
Beispiel #10
0
    def test_draw_centered(self):
        """
        Test that the drawn population is centered along the y-axis position.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        population, rows = 25, 5
        drawn = viz.draw_population(population, rows, '')
        for column in drawn:
            bb_top = util.get_bb(viz.figure, viz.axes, column[0])
            bb_bottom = util.get_bb(viz.figure, viz.axes, column[-1])
            self.assertEqual(0.5, (bb_top.y1 + bb_bottom.y0) / 2)
Beispiel #11
0
    def _fit_axes(self):
        """
        Make space for the x-axes.
        This function reduces the actual plot size so that the axes tick labels fit neatly.

        After it does that, it re-positions all of the labels on the left and right so they do not overlap with the axes.
        Here again, the axes are widened to fit the labels.
        """

        figure, axes, secondary = self.drawable.figure, self.drawable.axes, self.drawable.secondary

        if not self.llabels and not self.rlabels:
            super()._fit_axes()
            return

        _xlim = None
        while _xlim is None or abs(_xlim[0] - axes.get_xlim()[0]
                                   ) > 1e-10:  # repeat until convergence
            _xlim = axes.get_xlim()

            # draw the labels to get an idea of their widths
            for label in self.llabels + self.rlabels:
                label.redraw()
            lwidth = min(
                1,
                max(label.get_virtual_bb().width
                    for label in self.llabels) if self.llabels else 0)
            rwidth = min(
                1,
                max(label.get_virtual_bb().width
                    for label in self.rlabels) if self.rlabels else 0)
            lpad = 0.1 if self.llabels else 0
            rpad = 0.1 if self.rlabels else 0

            # find the new x-limit
            xlim = axes.get_xlim()
            x0 = min(
                util.get_bb(figure, axes, tick).x0 for tick in
                axes.get_yticklabels()) if axes.get_yticklabels() else -0.1
            x1 = max(
                util.get_bb(figure, axes, tick).x1 for tick in secondary.
                get_yticklabels()) if secondary.get_yticklabels() else 1.1
            axes.set_xlim((x0 - lwidth - lpad, x1 + rwidth + rpad))

            # move the left labels
            for label in self.llabels:
                label.x = (x0 - 1 - lpad, x0 - lpad)

            # move the right labels
            for label in self.rlabels:
                label.x = (x1 + rpad, x1 + 1 + rpad)
	def test_center_multiple_even_lines(self):
		"""
		Test that when centering multiple even lines, the block is centered around the given point.
		"""

		text = 'Memphis Depay, commonly known simply as Memphis, is a Dutch professional footballer and music artist who plays as a forward and captains French club Lyon and plays for the Netherlands national team. He is known for his pace, ability to cut inside, dribbling, distance shooting and ability to play the ball off the ground. Depay began his professional career with PSV Eindhoven.'
		viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
		annotation = Annotation(viz)
		lines = annotation.draw(text, (0, 1), 0, va='center')
		self.assertGreater(len(lines), 1)
		self.assertFalse(len(lines) % 2)
		tokens = [ tokens[0] for tokens in lines ]
		bb1 = util.get_bb(viz.figure, viz.axis, tokens[0])
		bb2 = util.get_bb(viz.figure, viz.axis, tokens[-1])
		self.assertEqual(0, round((bb1.y1 + bb2.y0) / 2., 10))
	def test_get_virtual_bb_multiple_lines(self):
		"""
		Test that the virtual bounding box of an annotation with multiple lines spans the entire block.
		"""

		text = 'Memphis Depay, commonly known simply as Memphis, is a Dutch professional footballer and music artist who plays as a forward and captains French club Lyon and plays for the Netherlands national team. He is known for his pace, ability to cut inside, dribbling, distance shooting and ability to play the ball off the ground.'
		viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
		annotation = Annotation(viz)
		lines = annotation.draw(text, (0, 1), 0)
		self.assertGreater(len(lines), 1)
		virtual_bb = annotation.get_virtual_bb()
		self.assertEqual(util.get_bb(viz.figure, viz.axis, lines[0][0]).x0, virtual_bb.x0)
		self.assertEqual(util.get_bb(viz.figure, viz.axis, lines[-1][-1]).y0, virtual_bb.y0)
		self.assertEqual(max(util.get_bb(viz.figure, viz.axis, lines[line][-1]).x1 for line in range(0, len(lines))), virtual_bb.x1)
		self.assertEqual(util.get_bb(viz.figure, viz.axis, lines[0][0]).y1, virtual_bb.y1)
	def test_align_bottom_lines_do_not_overlap(self):
		"""
		Test that when annotations are vertically aligned to the bottom, the lines do not overlap.
		"""

		text = 'Memphis Depay, commonly known simply as Memphis, is a Dutch professional footballer and music artist who plays as a forward and captains French club Lyon and plays for the Netherlands national team. He is known for his pace, ability to cut inside, dribbling, distance shooting and ability to play the ball off the ground.'
		viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
		annotation = Annotation(viz)
		lines = annotation.draw(text, (0, 1), 0, va='bottom')

		for i in range(0, len(lines) - 1):
			bb0 = util.get_bb(viz.figure, viz.axis, lines[i][0])
			bb1 = util.get_bb(viz.figure, viz.axis, lines[i + 1][0])

			self.assertGreaterEqual(bb0.y0, bb1.y1)
	def test_get_virtual_bb_line(self):
		"""
		Test that the virtual bounding box of an annotation with one line spans the entire line.
		"""

		text = 'Memphis Depay plays for Olympique Lyonnais'
		viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
		annotation = Annotation(viz)
		lines = annotation.draw(text, (0, 1), 0)
		self.assertEqual(1, len(lines))
		virtual_bb = annotation.get_virtual_bb()
		self.assertEqual(util.get_bb(viz.figure, viz.axis, lines[0][0]).x0, virtual_bb.x0)
		self.assertEqual(util.get_bb(viz.figure, viz.axis, lines[0][0]).y0, virtual_bb.y0)
		self.assertEqual(util.get_bb(viz.figure, viz.axis, lines[0][-1]).x1, virtual_bb.x1)
		self.assertEqual(util.get_bb(viz.figure, viz.axis, lines[0][-1]).y1, virtual_bb.y1)
Beispiel #16
0
    def get_virtual_bb(self, transform=None):
        """
		Get the bounding box of the entire annotation.
		This is called a virtual bounding box because it is not a real bounding box.
		Rather, it is a bounding box that covers all of the bounding boxes of the annotation's tokens.

		:param transform: The bounding box transformation.
						  If `None` is given, the data transformation is used.
		:type transform: None or :class:`matplotlib.transforms.TransformNode`

		:return: The bounding box of the annotation.
		:rtype: :class:`matplotlib.transforms.Bbox`
		"""

        figure = self.drawable.figure
        axis = self.drawable.axis

        transform = axis.transData if transform is None else transform
        renderer = figure.canvas.get_renderer()
        """
		Go through all the lines and their tokens and get their bounding boxes.
		Compare them with the virtual bounding box and update it as need be.
		"""
        x0, y0, x1, y1 = None, None, None, None
        for line in self.lines:
            for token in line:
                bb = util.get_bb(figure, axis, token, transform)
                x0 = bb.x0 if x0 is None or bb.x0 < x0 else x0
                y0 = bb.y0 if y0 is None or bb.y0 < y0 else y0
                x1 = bb.x1 if x1 is None or bb.x1 > x1 else x1
                y1 = bb.y1 if y1 is None or bb.y1 > y1 else y1

        return Bbox(((x0, y0), (x1, y1)))
	def test_align_bottom_line_alignment(self):
		"""
		Test that the lines all have the same vertical position when they are aligned to the top.
		"""

		text = 'Memphis Depay, commonly known simply as Memphis, is a Dutch professional footballer and music artist who plays as a forward and captains French club Lyon and plays for the Netherlands national team. He is known for his pace, ability to cut inside, dribbling, distance shooting and ability to play the ball off the ground.'
		viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
		annotation = Annotation(viz)
		lines = annotation.draw(text, (0, 1), 0, va='bottom')

		for line in lines:
			bb = util.get_bb(viz.figure, viz.axis, line[0])
			y1 = bb.y1

			for token in line:
				bb = util.get_bb(viz.figure, viz.axis, token)
				self.assertEqual(y1, bb.y1)
Beispiel #18
0
    def test_draw_columns_align(self):
        """
        Test that the drawn points align along the same column.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        population, rows = 13, 3
        drawn = viz.draw_population(population, rows, '')

        # test that each column's points have the same x0 and x1
        for column in drawn:
            bb = util.get_bb(viz.figure, viz.axes, column[0])
            for point in column[1:]:
                _bb = util.get_bb(viz.figure, viz.axes, point)
                self.assertEqual(bb.x0, _bb.x0)
                self.assertEqual(bb.x1, _bb.x1)
                self.assertEqual(bb.width, _bb.width)
Beispiel #19
0
    def test_redraw_multiple_lines(self):
        """
        Test that when the x-axis label is at the top, the legend moves all lines up.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 5)))
        figure, axes = viz.figure, viz.axes
        for i in range(0, 20):
            viz.legend.draw_line(f"label { i }")
        legend_bb = viz.legend.get_virtual_bb(transform=axes.transAxes)
        self.assertGreater(len(viz.legend.lines), 1)
        """
        Move the x-axis label and ticks to the top.
        """
        viz.axes.xaxis.set_label_position('top')
        viz.axes.xaxis.tick_top()
        viz.axes.spines['top'].set_visible(True)
        viz.axes.spines['bottom'].set_visible(False)
        """
        After adding a label, the legend should move up.
        """
        viz.set_xlabel('label')
        before_annotations = [
            annotation.get_virtual_bb(transform=axes.transAxes)
            for line in viz.legend.lines for _, annotation in line
        ]
        before_visuals = [
            util.get_bb(figure, axes, visual, transform=axes.transAxes)
            for line in viz.legend.lines for visual, _ in line
        ]
        viz.legend.redraw()
        after_annotations = [
            annotation.get_virtual_bb(transform=axes.transAxes)
            for line in viz.legend.lines for _, annotation in line
        ]
        after_visuals = [
            util.get_bb(figure, axes, visual, transform=axes.transAxes)
            for line in viz.legend.lines for visual, _ in line
        ]
        self.assertTrue(
            all(a1.y0 < a2.y0
                for a1, a2 in zip(before_annotations, after_annotations)))
        self.assertTrue(
            all(v1.y0 < v2.y0
                for v1, v2 in zip(before_visuals, after_visuals)))
Beispiel #20
0
    def test_new_point(self):
        """
        Test that when creating a new point, the legend starts at x-coordinate 0.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        point, annotation = viz.legend.draw_point('A')
        bb = util.get_bb(viz.figure, viz.axes, point)
        self.assertEqual(0, round(bb.x0, 1))
Beispiel #21
0
    def test_draw_columns_equidistant(self):
        """
        Test that the columns are separated with the same gap.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        population, rows = 10, 5
        drawn = viz.draw_population(population, rows, '')

        # test that each columns is equidistant from the next
        bb = util.get_bb(viz.figure, viz.axes, drawn[0][0])
        bb_next = util.get_bb(viz.figure, viz.axes, drawn[1][0])
        self.assertLess(bb.x1, bb_next.x0)
        gap = bb.x1 - bb_next.x0
        for i in range(len(drawn)):
            bb = util.get_bb(viz.figure, viz.axes, drawn[0][0])
            bb_next = util.get_bb(viz.figure, viz.axes, drawn[1][0])
            self.assertEqual(gap, bb.x1 - bb_next.x0)
Beispiel #22
0
    def test_visual_annotation_do_not_overlap(self):
        """
        Test that when drawing a legend, the visual and the annotation do not overlap.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        line, annotation = viz.legend.draw_line('A')
        linebb = util.get_bb(viz.figure, viz.axes, line)
        self.assertFalse(util.overlapping_bb(linebb, annotation.get_virtual_bb()))
Beispiel #23
0
    def test_align_justify_center(self):
        """
		Test that when justifying text with the last line centered, all lines have the exact same center.
		"""

        text = 'Memphis Depay, commonly known simply as Memphis, is a Dutch professional footballer and music artist who plays as a forward and captains French club Lyon and plays for the Netherlands national team. He is known for his pace, ability to cut inside, dribbling, distance shooting and ability to play the ball off the ground.'
        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        lines = viz.draw_text_annotation(text, align='justify-center')

        x = 0
        for i, (_, tokens) in enumerate(lines):
            bb0 = util.get_bb(viz.figure, viz.axis, tokens[0])
            bb1 = util.get_bb(viz.figure, viz.axis, tokens[-1])
            center = (bb0.x0 + bb1.x1) / 2.
            if i == 0:
                x = center

            self.assertEqual(round(x, 5), round(center, 5))
Beispiel #24
0
    def redraw(self):
        """
		Redraw the legend.
		This function only has an effect when the x-axis label and ticks are at the top, instead of at the bottom.
		In this case, this function moves the legend up to make room for the label and ticks.
		"""

        figure, axes = self.drawable.figure, self.drawable.axes
        """
		If the legend is empty, do nothing.
		"""
        if not (self.lines[-1]):
            return
        """
		Get the position at which the legend should be.
		"""
        y = 1.05
        if axes.xaxis.get_label_position() == 'top':
            y += self.drawable._get_xlabel(transform=axes.transAxes).height * 2

            xtick_labels_bb = self.drawable._get_xtick_labels(
                transform=axes.transAxes)
            if xtick_labels_bb:
                y += max(xtick_labels_bb, key=lambda bb: bb.height).height * 2
        """
		Get the position of the last line.
		"""
        bottom = self.get_virtual_bb(transform=axes.transAxes).y0
        """
		If the legend is below the x-axis label and tick labels, move all lines up by that amount.
		"""
        if bottom < y:
            offset = y - bottom
            for line in self.lines:
                for (visual, annotation) in line:
                    """
					Move the visual first, then the text.
					"""
                    if visual:
                        bb = util.get_bb(figure,
                                         axes,
                                         visual,
                                         transform=axes.transAxes)
                        if type(visual) == lines.Line2D:
                            visual.set_ydata([bb.y0 + offset] * 2)
                        elif type(visual) == text.Annotation:
                            visual.xyann = (bb.x0, bb.y1 + offset)
                            visual.xy = (bb.x1, bb.y1 + offset)
                        elif type(visual) == collections.PathCollection:
                            offsets = visual.get_offsets()[0]
                            visual.set_offsets(
                                [[offsets[0], offsets[1] + offset]])

                    bb = annotation.get_virtual_bb(transform=axes.transAxes)
                    annotation.set_position((bb.x0, bb.y0 + offset),
                                            transform=axes.transAxes)
Beispiel #25
0
    def test_draw_bars_0_pad(self):
        """
		Test that when drawing bars, they all start at 0 even when padding is given.
		"""

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        bar = Bar100(viz)
        values = bar._to_dict(list(range(10)))
        bars = bar._draw_bars(values, pad=1)
        self.assertEqual(0, util.get_bb(viz.figure, viz.axes, bars[0]).x0)
Beispiel #26
0
    def test_draw_bars_100_pad(self):
        """
        Test that when drawing bars, they all end at 100 even when padding is given.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        bar = Bar100(viz)
        values = bar._to_dict(list(range(10)))
        bars = bar._draw_bars(values, min_percentage=2, pad=1)
        self.assertEqual(100, round(util.get_bb(viz.figure, viz.axes, bars[-1]).x1, 7))
	def test_align_center(self):
		"""
		Test that when centering text, all of the lines' centers are the same.
		"""

		text = 'Memphis Depay, commonly known simply as Memphis, is a Dutch professional footballer and music artist who plays as a forward and captains French club Lyon and plays for the Netherlands national team. He is known for his pace, ability to cut inside, dribbling, distance shooting and ability to play the ball off the ground.'
		viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
		annotation = Annotation(viz)
		lines = annotation.draw(text, (0, 2), 0, align='center', va='top')

		x = 0
		for i, lines in enumerate(lines[:-1]):
			bb0 = util.get_bb(viz.figure, viz.axis, lines[0])
			bb1 = util.get_bb(viz.figure, viz.axis, lines[-1])
			center = (bb0.x0 + bb1.x1) / 2.
			if i == 0:
				x = center

			self.assertEqual(round(x, 5), round(center, 5))
Beispiel #28
0
    def test_draw_bars_min_percentage(self):
        """
        Test that when drawing bars, the minimum percentage is respected.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        bar = Bar100(viz)
        values = bar._to_dict([ 0, 1, 2, 3 ])
        bars = bar._draw_bars(values, min_percentage=10)
        self.assertTrue(all( round(util.get_bb(viz.figure, viz.axes, bar).width, 10) >= 10 for bar in bars ))
Beispiel #29
0
    def test_overlapping_inverted_y(self):
        """
        Test that when the y-axis is inverted, the overlapping test adapts the bounding boxes.
        """

        # first test the normal behavior of the bounding box
        viz = drawable.Drawable(plt.figure(figsize=(5, 5)))
        text = viz.text(0, 0, 'piece of text')
        bb = util.get_bb(viz.figure, viz.axes, text)
        self.assertLess(bb.y0, bb.y1)

        # test that when inverting the y-axis, the y-coordinates of the bounding box change
        viz.invert_yaxis()
        bb = util.get_bb(viz.figure, viz.axes, text)
        self.assertGreater(bb.y0, bb.y1)

        # create overlapping bounding boxes that emulate an inverted y-axis and test
        bb1, bb2 = Bbox(((0, 1), (1, 0))), Bbox(((0.5, 1.5), (1.5, 0.5)))
        self.assertTrue(util.overlapping_bb(bb1, bb2))
Beispiel #30
0
    def test_draw_bars_100(self):
        """
        Test that when drawing bars, they all end at 100.
        """

        viz = drawable.Drawable(plt.figure(figsize=(10, 10)))
        bar = Bar100(viz)
        values = bar._to_dict(list(range(10)))
        bars = bar._draw_bars(values)
        self.assertEqual(100, round(util.get_bb(viz.figure, viz.axes, bars[-1]).x1, 7))