Beispiel #1
0
    def __init__(self, value, parent=None):
        QtWidgets.QGridLayout.__init__(self)
        font = tuple_to_qfont(value)
        assert font is not None

        # Font family
        self.family = QtWidgets.QFontComboBox(parent)
        self.family.setCurrentFont(font)
        self.addWidget(self.family, 0, 0, 1, -1)

        # Font size
        self.size = QtWidgets.QComboBox(parent)
        self.size.setEditable(True)
        sizelist = list(xrange(6, 12)) + list(xrange(12, 30, 2)) + [36, 48, 72]
        size = font.pointSize()
        if size not in sizelist:
            sizelist.append(size)
            sizelist.sort()
        self.size.addItems([str(s) for s in sizelist])
        self.size.setCurrentIndex(sizelist.index(size))
        self.addWidget(self.size, 1, 0)

        # Italic or not
        self.italic = QtWidgets.QCheckBox(self.tr("Italic"), parent)
        self.italic.setChecked(font.italic())
        self.addWidget(self.italic, 1, 1)

        # Bold or not
        self.bold = QtWidgets.QCheckBox(self.tr("Bold"), parent)
        self.bold.setChecked(font.bold())
        self.addWidget(self.bold, 1, 2)
Beispiel #2
0
    def add_lines(self, levels, colors, linewidths, erase=True):
        '''
        Draw lines on the colorbar.

        *colors* and *linewidths* must be scalars or
        sequences the same length as *levels*.

        Set *erase* to False to add lines without first
        removing any previously added lines.
        '''
        y = self._locate(levels)
        igood = (y < 1.001) & (y > -0.001)
        y = y[igood]
        if cbook.iterable(colors):
            colors = np.asarray(colors)[igood]
        if cbook.iterable(linewidths):
            linewidths = np.asarray(linewidths)[igood]
        N = len(y)
        x = np.array([0.0, 1.0])
        X, Y = np.meshgrid(x, y)
        if self.orientation == 'vertical':
            xy = [list(zip(X[i], Y[i])) for i in xrange(N)]
        else:
            xy = [list(zip(Y[i], X[i])) for i in xrange(N)]
        col = collections.LineCollection(xy, linewidths=linewidths)

        if erase and self.lines:
            for lc in self.lines:
                lc.remove()
            self.lines = []
        self.lines.append(col)
        col.set_color(colors)
        self.ax.add_collection(col)
        self.stale = True
Beispiel #3
0
def test_simple():
    fig = plt.figure()
    # un-comment to debug
    #    recursive_pickle(fig)
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.subplot(121)
    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.axes(projection='polar')
    plt.plot(list(xrange(10)), label='foobar')
    plt.legend()

    # Uncomment to debug any unpicklable objects. This is slow so is not
    # uncommented by default.
    #    recursive_pickle(fig)
    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    #    ax = plt.subplot(121, projection='hammer')
    #    recursive_pickle(ax, 'figure')
    #    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    plt.figure()
    plt.bar(left=list(xrange(10)), height=list(xrange(10)))
    pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)

    fig = plt.figure()
    ax = plt.axes()
    plt.plot(list(xrange(10)))
    ax.set_yscale('log')
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
Beispiel #4
0
    def add_lines(self, levels, colors, linewidths, erase=True):
        '''
        Draw lines on the colorbar.

        *colors* and *linewidths* must be scalars or
        sequences the same length as *levels*.

        Set *erase* to False to add lines without first
        removing any previously added lines.
        '''
        y = self._locate(levels)
        igood = (y < 1.001) & (y > -0.001)
        y = y[igood]
        if cbook.iterable(colors):
            colors = np.asarray(colors)[igood]
        if cbook.iterable(linewidths):
            linewidths = np.asarray(linewidths)[igood]
        N = len(y)
        x = np.array([0.0, 1.0])
        X, Y = np.meshgrid(x, y)
        if self.orientation == 'vertical':
            xy = [list(zip(X[i], Y[i])) for i in xrange(N)]
        else:
            xy = [list(zip(Y[i], X[i])) for i in xrange(N)]
        col = collections.LineCollection(xy, linewidths=linewidths)

        if erase and self.lines:
            for lc in self.lines:
                lc.remove()
            self.lines = []
        self.lines.append(col)
        col.set_color(colors)
        self.ax.add_collection(col)
        self.stale = True
Beispiel #5
0
def test_simple():
    fig = plt.figure()
    # un-comment to debug
#    recursive_pickle(fig)
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.subplot(121)
    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    ax = plt.axes(projection='polar')
    plt.plot(list(xrange(10)), label='foobar')
    plt.legend()

    # Uncomment to debug any unpicklable objects. This is slow so is not
    # uncommented by default.
#    recursive_pickle(fig)
    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

#    ax = plt.subplot(121, projection='hammer')
#    recursive_pickle(ax, 'figure')
#    pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)

    plt.figure()
    plt.bar(left=list(xrange(10)), height=list(xrange(10)))
    pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)

    fig = plt.figure()
    ax = plt.axes()
    plt.plot(list(xrange(10)))
    ax.set_yscale('log')
    pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
Beispiel #6
0
def test_fancy():
    # using subplot triggers some offsetbox functionality untested elsewhere
    plt.subplot(121)
    plt.scatter(list(xrange(10)), list(xrange(10, 0, -1)), label='XX\nXX')
    plt.plot([5] * 10, 'o--', label='XX')
    plt.errorbar(list(xrange(10)), list(xrange(10)), xerr=0.5, yerr=0.5, label='XX')
    plt.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],
               ncol=2, shadow=True, title="My legend", numpoints=1)
def test_various_labels():
    # tests all sorts of label types
    fig = plt.figure()
    ax = fig.add_subplot(121)
    ax.plot(list(xrange(4)), 'o', label=1)
    ax.plot(np.linspace(4, 4.1), 'o', label='D\xe9velopp\xe9s')
    ax.plot(list(xrange(4, 1, -1)), 'o', label='__nolegend__')
    ax.legend(numpoints=1, loc=0)
Beispiel #8
0
def test_various_labels():
    # tests all sorts of label types
    fig = plt.figure()
    ax = fig.add_subplot(121)
    ax.plot(list(xrange(4)), 'o', label=1)
    ax.plot(np.linspace(4, 4.1), 'o', label='D\xe9velopp\xe9s')
    ax.plot(list(xrange(4, 1, -1)), 'o', label='__nolegend__')
    ax.legend(numpoints=1, loc=0)
Beispiel #9
0
 def _edges(self, X, Y):
     '''
     Return the separator line segments; helper for _add_solids.
     '''
     N = X.shape[0]
     # Using the non-array form of these line segments is much
     # simpler than making them into arrays.
     if self.orientation == 'vertical':
         return [list(zip(X[i], Y[i])) for i in xrange(1, N - 1)]
     else:
         return [list(zip(Y[i], X[i])) for i in xrange(1, N - 1)]
Beispiel #10
0
 def _edges(self, X, Y):
     '''
     Return the separator line segments; helper for _add_solids.
     '''
     N = X.shape[0]
     # Using the non-array form of these line segments is much
     # simpler than making them into arrays.
     if self.orientation == 'vertical':
         return [list(zip(X[i], Y[i])) for i in xrange(1, N - 1)]
     else:
         return [list(zip(Y[i], X[i])) for i in xrange(1, N - 1)]
Beispiel #11
0
def test_rc():
    # using subplot triggers some offsetbox functionality untested elsewhere
    fig = plt.figure()
    ax = plt.subplot(121)
    ax.scatter(list(xrange(10)), list(xrange(10, 0, -1)), label='three')
    ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], title="My legend")

    mpl.rcParams['legend.scatterpoints'] = 1
    fig = plt.figure()
    ax = plt.subplot(121)
    ax.scatter(list(xrange(10)), list(xrange(10, 0, -1)), label='one')
    ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5], title="My legend")
def test_rc():
    # using subplot triggers some offsetbox functionality untested elsewhere
    fig = plt.figure()
    ax = plt.subplot(121)
    ax.scatter(list(xrange(10)), list(xrange(10, 0, -1)), label='three')
    ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],
              title="My legend")

    mpl.rcParams['legend.scatterpoints'] = 1
    fig = plt.figure()
    ax = plt.subplot(121)
    ax.scatter(list(xrange(10)), list(xrange(10, 0, -1)), label='one')
    ax.legend(loc="center left", bbox_to_anchor=[1.0, 0.5],
              title="My legend")
Beispiel #13
0
    def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        # Save, set, and restore hold state to keep pcolor from
        # clearing the axes. Ordinarily this will not be needed,
        # since the axes object should already have hold set.
        _hold = self.ax.ishold()
        self.ax.hold(True)

        kw = {
            'alpha': self.alpha,
        }

        n_segments = len(C)

        # ensure there are sufficent hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in xrange(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]], [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch,
                                       linewidth=0,
                                       antialiased=False,
                                       **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(
                self._edges(X, Y),
                colors=(mpl.rcParams['axes.edgecolor'], ),
                linewidths=(0.5 * mpl.rcParams['axes.linewidth'], ))
            self.ax.add_collection(self.dividers)

        self.ax.hold(_hold)
    def updatePlot(self):
        w, h = self.canvas.get_width_height()

        # Remove all previous images
        for i in xrange(self.image_.representations().count()):
            self.image_.removeRepresentation_(
                self.image_.representations().objectAtIndex_(i))

        self.image_.setSize_((w, h))

        brep = NSBitmapImageRep.alloc(
        ).initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel_(
            (self.canvas.buffer_rgba(), '', '', '', ''),  # Image data
            w,  # width
            h,  # height
            8,  # bits per pixel
            4,  # components per pixel
            True,  # has alpha?
            False,  # is planar?
            NSCalibratedRGBColorSpace,  # color space
            w * 4,  # row bytes
            32)  # bits per pixel

        self.image_.addRepresentation_(brep)
        self.setNeedsDisplay_(True)
Beispiel #15
0
    def set_vertices_and_codes(self, vertices, codes):
        offset = 1.0 / self.num_rows
        shape_vertices = self.shape_vertices * offset * self.size
        if not self.filled:
            inner_vertices = shape_vertices[::-1] * 0.9
        shape_codes = self.shape_codes
        shape_size = len(shape_vertices)

        cursor = 0
        for row in xrange(self.num_rows + 1):
            if row % 2 == 0:
                cols = np.linspace(0.0, 1.0, self.num_rows + 1, True)
            else:
                cols = np.linspace(offset / 2.0, 1.0 - offset / 2.0,
                                   self.num_rows, True)
            row_pos = row * offset
            for col_pos in cols:
                vertices[cursor:cursor + shape_size] = (shape_vertices +
                                                        (col_pos, row_pos))
                codes[cursor:cursor + shape_size] = shape_codes
                cursor += shape_size
                if not self.filled:
                    vertices[cursor:cursor + shape_size] = (inner_vertices +
                                                            (col_pos, row_pos))
                    codes[cursor:cursor + shape_size] = shape_codes
                    cursor += shape_size
Beispiel #16
0
    def __init__(self, filename):
        matplotlib.verbose.report('opening tfm file ' + filename, 'debug')
        with open(filename, 'rb') as file:
            header1 = file.read(24)
            lh, bc, ec, nw, nh, nd = \
                struct.unpack(str('!6H'), header1[2:14])
            matplotlib.verbose.report(
                'lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d' %
                (lh, bc, ec, nw, nh, nd), 'debug')
            header2 = file.read(4 * lh)
            self.checksum, self.design_size = \
                struct.unpack(str('!2I'), header2[:8])
            # there is also encoding information etc.
            char_info = file.read(4 * (ec - bc + 1))
            widths = file.read(4 * nw)
            heights = file.read(4 * nh)
            depths = file.read(4 * nd)

        self.width, self.height, self.depth = {}, {}, {}
        widths, heights, depths = \
            [struct.unpack(str('!%dI') % (len(x)/4), x)
             for x in (widths, heights, depths)]
        for idx, char in enumerate(xrange(bc, ec + 1)):
            byte0 = ord(char_info[4 * idx])
            byte1 = ord(char_info[4 * idx + 1])
            self.width[char] = _fix2comp(widths[byte0])
            self.height[char] = _fix2comp(heights[byte1 >> 4])
            self.depth[char] = _fix2comp(depths[byte1 & 0xf])
Beispiel #17
0
def test_bbox_inches_tight():
    #: Test that a figure saved using bbox_inches='tight' is clipped correctly
    data = [[66386, 174296, 75131, 577908, 32015],
            [58230, 381139, 78045, 99308, 160454],
            [89135, 80552, 152558, 497981, 603535],
            [78415, 81858, 150656, 193263, 69638],
            [139361, 331509, 343164, 781380, 52269]]

    colLabels = rowLabels = [''] * 5

    rows = len(data)
    ind = np.arange(len(colLabels)) + 0.3  # the x locations for the groups
    cellText = []
    width = 0.4  # the width of the bars
    yoff = np.array([0.0] * len(colLabels))
    # the bottom values for stacked bar chart
    fig, ax = plt.subplots(1, 1)
    for row in xrange(rows):
        plt.bar(ind, data[row], width, bottom=yoff)
        yoff = yoff + data[row]
        cellText.append([''])
    plt.xticks([])
    plt.legend([''] * 5, loc=(1.2, 0.2))
    # Add a table at the bottom of the axes
    cellText.reverse()
    the_table = plt.table(cellText=cellText,
                          rowLabels=rowLabels,
                          colLabels=colLabels,
                          loc='bottom')
Beispiel #18
0
    def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
        """
        Place the *bbox* inside the *parentbbox* according to a given
        location code. Return the (x,y) coordinate of the bbox.

        - loc: a location code in range(1, 11).
          This corresponds to the possible values for self._loc, excluding
          "best".

        - bbox: bbox to be placed, display coodinate units.
        - parentbbox: a parent box which will contain the bbox. In
            display coordinates.
        """
        assert loc in range(1, 11)  # called only internally

        BEST, UR, UL, LL, LR, R, CL, CR, LC, UC, C = list(xrange(11))

        anchor_coefs = {UR: "NE",
                        UL: "NW",
                        LL: "SW",
                        LR: "SE",
                        R: "E",
                        CL: "W",
                        CR: "E",
                        LC: "S",
                        UC: "N",
                        C: "C"}

        c = anchor_coefs[loc]

        fontsize = renderer.points_to_pixels(self._fontsize)
        container = parentbbox.padded(-(self.borderaxespad) * fontsize)
        anchored_box = bbox.anchored(c, container=container)
        return anchored_box.x0, anchored_box.y0
Beispiel #19
0
 def test_line_extents_affine(self):
     ax = plt.axes()
     offset = mtrans.Affine2D().translate(10, 10)
     plt.plot(list(xrange(10)), transform=offset + ax.transData)
     expeted_data_lim = np.array([[0., 0.], [9., 9.]]) + 10
     np.testing.assert_array_almost_equal(ax.dataLim.get_points(),
                                          expeted_data_lim)
def test_bbox_inches_tight():
    #: Test that a figure saved using bbox_inches='tight' is clipped correctly
    data = [[ 66386, 174296,  75131, 577908,  32015],
            [ 58230, 381139,  78045,  99308, 160454],
            [ 89135,  80552, 152558, 497981, 603535],
            [ 78415,  81858, 150656, 193263,  69638],
            [139361, 331509, 343164, 781380,  52269]]

    colLabels = rowLabels = [''] * 5

    rows = len(data)
    ind = np.arange(len(colLabels)) + 0.3  # the x locations for the groups
    cellText = []
    width = 0.4     # the width of the bars
    yoff = np.array([0.0] * len(colLabels))
    # the bottom values for stacked bar chart
    fig, ax = plt.subplots(1, 1)
    for row in xrange(rows):
        plt.bar(ind, data[row], width, bottom=yoff)
        yoff = yoff + data[row]
        cellText.append([''])
    plt.xticks([])
    plt.legend([''] * 5, loc=(1.2, 0.2))
    # Add a table at the bottom of the axes
    cellText.reverse()
    the_table = plt.table(cellText=cellText,
                          rowLabels=rowLabels,
                          colLabels=colLabels, loc='bottom')
 def test_line_extents_affine(self):
     ax = plt.axes()
     offset = mtrans.Affine2D().translate(10, 10)
     plt.plot(list(xrange(10)), transform=offset + ax.transData)
     expeted_data_lim = np.array([[0., 0.], [9.,  9.]]) + 10
     np.testing.assert_array_almost_equal(ax.dataLim.get_points(),
                                          expeted_data_lim)
Beispiel #22
0
    def __init__(self, filename):
        matplotlib.verbose.report('opening tfm file ' + filename, 'debug')
        with open(filename, 'rb') as file:
            header1 = file.read(24)
            lh, bc, ec, nw, nh, nd = \
                struct.unpack(str('!6H'), header1[2:14])
            matplotlib.verbose.report(
                'lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d' % (
                    lh, bc, ec, nw, nh, nd), 'debug')
            header2 = file.read(4*lh)
            self.checksum, self.design_size = \
                struct.unpack(str('!2I'), header2[:8])
            # there is also encoding information etc.
            char_info = file.read(4*(ec-bc+1))
            widths = file.read(4*nw)
            heights = file.read(4*nh)
            depths = file.read(4*nd)

        self.width, self.height, self.depth = {}, {}, {}
        widths, heights, depths = \
            [struct.unpack(str('!%dI') % (len(x)/4), x)
             for x in (widths, heights, depths)]
        for idx, char in enumerate(xrange(bc, ec+1)):
            byte0 = ord(char_info[4*idx])
            byte1 = ord(char_info[4*idx+1])
            self.width[char] = _fix2comp(widths[byte0])
            self.height[char] = _fix2comp(heights[byte1 >> 4])
            self.depth[char] = _fix2comp(depths[byte1 & 0xf])
Beispiel #23
0
    def set_vertices_and_codes(self, vertices, codes):
        offset = 1.0 / self.num_rows
        shape_vertices = self.shape_vertices * offset * self.size
        if not self.filled:
            inner_vertices = shape_vertices[::-1] * 0.9
        shape_codes = self.shape_codes
        shape_size = len(shape_vertices)

        cursor = 0
        for row in xrange(self.num_rows + 1):
            if row % 2 == 0:
                cols = np.linspace(0.0, 1.0, self.num_rows + 1, True)
            else:
                cols = np.linspace(offset / 2.0, 1.0 - offset / 2.0,
                                   self.num_rows, True)
            row_pos = row * offset
            for col_pos in cols:
                vertices[cursor:cursor + shape_size] = (shape_vertices +
                                                        (col_pos, row_pos))
                codes[cursor:cursor + shape_size] = shape_codes
                cursor += shape_size
                if not self.filled:
                    vertices[cursor:cursor + shape_size] = (inner_vertices +
                                                            (col_pos, row_pos))
                    codes[cursor:cursor + shape_size] = shape_codes
                    cursor += shape_size
def test_bbox_inches_tight_clipping():
    # tests bbox clipping on scatter points, and path clipping on a patch
    # to generate an appropriately tight bbox
    plt.scatter(list(xrange(10)), list(xrange(10)))
    ax = plt.gca()
    ax.set_xlim([0, 5])
    ax.set_ylim([0, 5])

    # make a massive rectangle and clip it with a path
    patch = mpatches.Rectangle([-50, -50], 100, 100,
                               transform=ax.transData,
                               facecolor='blue', alpha=0.5)

    path = mpath.Path.unit_regular_star(5).deepcopy()
    path.vertices *= 0.25
    patch.set_clip_path(path, transform=ax.transAxes)
    plt.gcf().artists.append(patch)
def test_1d_plots():
    x_range = slice(0.25, 9.75, 20j)
    x = np.mgrid[x_range]
    ax = plt.gca()
    for y in xrange(2, 10, 2):
        plt.plot(x, ref_interpolator[x_range, y:y:1j])
    ax.set_xticks([])
    ax.set_yticks([])
Beispiel #26
0
def test_1d_plots():
    x_range = slice(0.25,9.75,20j)
    x = np.mgrid[x_range]
    ax = plt.gca()
    for y in xrange(2,10,2):
        plt.plot(x, ref_interpolator[x_range,y:y:1j])
    ax.set_xticks([])
    ax.set_yticks([])
Beispiel #27
0
def test_bbox_inches_tight_clipping():
    # tests bbox clipping on scatter points, and path clipping on a patch
    # to generate an appropriately tight bbox
    plt.scatter(list(xrange(10)), list(xrange(10)))
    ax = plt.gca()
    ax.set_xlim([0, 5])
    ax.set_ylim([0, 5])

    # make a massive rectangle and clip it with a path
    patch = mpatches.Rectangle([-50, -50], 100, 100,
                               transform=ax.transData,
                               facecolor='blue', alpha=0.5)

    path = mpath.Path.unit_regular_star(5).deepcopy()
    path.vertices *= 0.25
    patch.set_clip_path(path, transform=ax.transAxes)
    plt.gcf().artists.append(patch)
Beispiel #28
0
    def add_lines(self, levels, colors, linewidths):
        '''
        Draw lines on the colorbar. It deletes preexisting lines.
        '''
        del self.lines

        N = len(levels)
        x = np.array([1.0, 2.0])
        X, Y = np.meshgrid(x,levels)
        if self.orientation == 'vertical':
            xy = [list(zip(X[i], Y[i])) for i in xrange(N)]
        else:
            xy = [list(zip(Y[i], X[i])) for i in xrange(N)]
        col = collections.LineCollection(xy, linewidths=linewidths,
                                         )
        self.lines = col
        col.set_color(colors)
        self.ax.add_collection(col)
Beispiel #29
0
    def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        # Save, set, and restore hold state to keep pcolor from
        # clearing the axes. Ordinarily this will not be needed,
        # since the axes object should already have hold set.
        _hold = self.ax.ishold()
        self.ax.hold(True)

        kw = {'alpha': self.alpha, }

        n_segments = len(C)

        # ensure there are sufficent hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in xrange(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]],
                           [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch, linewidth=0,
                                       antialiased=False, **kw)
            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(self._edges(X, Y),
                    colors=(mpl.rcParams['axes.edgecolor'],),
                    linewidths=(0.5 * mpl.rcParams['axes.linewidth'],))
            self.ax.add_collection(self.dividers)

        self.ax.hold(_hold)
Beispiel #30
0
    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        # Do any auto width setting
        for col in self._autoColumns:
            self._auto_set_column_width(col, renderer)

        if self._autoFontsize:
            self._auto_set_font_size(renderer)

        # Align all the cells
        self._do_cell_alignment()

        bbox = self._get_grid_bbox(renderer)
        l, b, w, h = bbox.bounds

        if self._bbox is not None:
            # Position according to bbox
            rl, rb, rw, rh = self._bbox
            self.scale(rw / w, rh / h)
            ox = rl - l
            oy = rb - b
            self._do_cell_alignment()
        else:
            # Position using loc
            (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C,
             TR, TL, BL, BR, R, L, T, B) = list(xrange(len(self.codes)))
            # defaults for center
            ox = (0.5 - w / 2) - l
            oy = (0.5 - h / 2) - b
            if self._loc in (UL, LL, CL):   # left
                ox = self.AXESPAD - l
            if self._loc in (BEST, UR, LR, R, CR):  # right
                ox = 1 - (l + w + self.AXESPAD)
            if self._loc in (BEST, UR, UL, UC):     # upper
                oy = 1 - (b + h + self.AXESPAD)
            if self._loc in (LL, LR, LC):           # lower
                oy = self.AXESPAD - b
            if self._loc in (LC, UC, C):            # center x
                ox = (0.5 - w / 2) - l
            if self._loc in (CL, CR, C):            # center y
                oy = (0.5 - h / 2) - b

            if self._loc in (TL, BL, L):            # out left
                ox = - (l + w)
            if self._loc in (TR, BR, R):            # out right
                ox = 1.0 - l
            if self._loc in (TR, TL, T):            # out top
                oy = 1.0 - b
            if self._loc in (BL, BR, B):           # out bottom
                oy = - (b + h)

        self._offset(ox, oy)
Beispiel #31
0
    def _update_positions(self, renderer):
        # called from renderer to allow more precise estimates of
        # widths and heights with get_window_extent

        # Do any auto width setting
        for col in self._autoColumns:
            self._auto_set_column_width(col, renderer)

        if self._autoFontsize:
            self._auto_set_font_size(renderer)

        # Align all the cells
        self._do_cell_alignment()

        bbox = self._get_grid_bbox(renderer)
        l, b, w, h = bbox.bounds

        if self._bbox is not None:
            # Position according to bbox
            rl, rb, rw, rh = self._bbox
            self.scale(rw / w, rh / h)
            ox = rl - l
            oy = rb - b
            self._do_cell_alignment()
        else:
            # Position using loc
            (BEST, UR, UL, LL, LR, CL, CR, LC, UC, C, TR, TL, BL, BR, R, L, T,
             B) = list(xrange(len(self.codes)))
            # defaults for center
            ox = (0.5 - w / 2) - l
            oy = (0.5 - h / 2) - b
            if self._loc in (UL, LL, CL):  # left
                ox = self.AXESPAD - l
            if self._loc in (BEST, UR, LR, R, CR):  # right
                ox = 1 - (l + w + self.AXESPAD)
            if self._loc in (BEST, UR, UL, UC):  # upper
                oy = 1 - (b + h + self.AXESPAD)
            if self._loc in (LL, LR, LC):  # lower
                oy = self.AXESPAD - b
            if self._loc in (LC, UC, C):  # center x
                ox = (0.5 - w / 2) - l
            if self._loc in (CL, CR, C):  # center y
                oy = (0.5 - h / 2) - b

            if self._loc in (TL, BL, L):  # out left
                ox = -(l + w)
            if self._loc in (TR, BR, R):  # out right
                ox = 1.0 - l
            if self._loc in (TR, TL, T):  # out top
                oy = 1.0 - b
            if self._loc in (BL, BR, B):  # out bottom
                oy = -(b + h)

        self._offset(ox, oy)
Beispiel #32
0
def check_shared(results, f, axs):
    """
    results is a 4 x 4 x 2 matrix of boolean values where
        if [i, j, 0] == True, X axis for subplots i and j should be shared
        if [i, j, 1] == False, Y axis for subplots i and j should not be shared
    """
    shared_str = ['x', 'y']
    shared = [axs[0]._shared_x_axes, axs[0]._shared_y_axes]
    #shared = {
    #        'x': a1._shared_x_axes,
    #        'y': a1._shared_y_axes,
    #        }
    tostr = lambda r: "not " if r else ""
    for i1 in xrange(len(axs)):
        for i2 in xrange(i1 + 1, len(axs)):
            for i3 in xrange(len(shared)):
                assert shared[i3].joined(axs[i1], axs[i2]) == \
                        results[i1, i2, i3], \
                        "axes %i and %i incorrectly %ssharing %s axis" % \
                        (i1, i2, tostr(results[i1, i2, i3]), shared_str[i3])
Beispiel #33
0
    def add_lines(self, levels, colors, linewidths):
        '''
        Draw lines on the colorbar. It deletes preexisting lines.
        '''
        del self.lines

        N = len(levels)
        x = np.array([1.0, 2.0])
        X, Y = np.meshgrid(x, levels)
        if self.orientation == 'vertical':
            xy = [list(zip(X[i], Y[i])) for i in xrange(N)]
        else:
            xy = [list(zip(Y[i], X[i])) for i in xrange(N)]
        col = collections.LineCollection(
            xy,
            linewidths=linewidths,
        )
        self.lines = col
        col.set_color(colors)
        self.ax.add_collection(col)
def check_shared(results, f, axs):
    """
    results is a 4 x 4 x 2 matrix of boolean values where
        if [i, j, 0] == True, X axis for subplots i and j should be shared
        if [i, j, 1] == False, Y axis for subplots i and j should not be shared
    """
    shared_str = ['x', 'y']
    shared = [axs[0]._shared_x_axes, axs[0]._shared_y_axes]
    #shared = {
    #        'x': a1._shared_x_axes,
    #        'y': a1._shared_y_axes,
    #        }
    tostr = lambda r: "not " if r else ""
    for i1 in xrange(len(axs)):
        for i2 in xrange(i1 + 1, len(axs)):
            for i3 in xrange(len(shared)):
                assert shared[i3].joined(axs[i1], axs[i2]) == \
                        results[i1, i2, i3], \
                        "axes %i and %i incorrectly %ssharing %s axis" % \
                        (i1, i2, tostr(results[i1, i2, i3]), shared_str[i3])
Beispiel #35
0
    def test_line_extents_for_non_affine_transData(self):
        ax = plt.axes(projection="polar")
        # add 10 to the radius of the data
        offset = mtrans.Affine2D().translate(0, 10)

        plt.plot(list(xrange(10)), transform=offset + ax.transData)
        # the data lim of a polar plot is stored in coordinates
        # before a transData transformation, hence the data limits
        # are not what is being shown on the actual plot.
        expeted_data_lim = np.array([[0.0, 0.0], [9.0, 9.0]]) + [0, 10]
        np.testing.assert_array_almost_equal(ax.dataLim.get_points(), expeted_data_lim)
Beispiel #36
0
    def __init__(self,  bymonthday=None, interval=1, tz=None):
        """
        Mark every day in *bymonthday*; *bymonthday* can be an int or
        sequence.

        Default is to tick every day of the month: ``bymonthday=range(1,32)``
        """
        if bymonthday is None:
            bymonthday = list(xrange(1, 32))
        o = rrulewrapper(DAILY, bymonthday=bymonthday,
                         interval=interval, **self.hms0d)
        RRuleLocator.__init__(self, o, tz)
Beispiel #37
0
 def __init__(self, scale, tfm, texname, vf):
     if six.PY3 and isinstance(texname, bytes):
         texname = texname.decode('ascii')
     self._scale, self._tfm, self.texname, self._vf = \
         scale, tfm, texname, vf
     self.size = scale * (72.0 / (72.27 * 2**16))
     try:
         nchars = max(six.iterkeys(tfm.width)) + 1
     except ValueError:
         nchars = 0
     self.widths = [(1000*tfm.width.get(char, 0)) >> 20
                    for char in xrange(nchars)]
Beispiel #38
0
def test_figure():
    # named figure support
    fig = plt.figure('today')
    ax = fig.add_subplot(111)
    ax.set_title(fig.get_label())
    ax.plot(list(xrange(5)))
    # plot red line in a different figure.
    plt.figure('tomorrow')
    plt.plot([0, 1], [1, 0], 'r')
    # Return to the original; make sure the red line is not there.
    plt.figure('today')
    plt.close('tomorrow')
Beispiel #39
0
 def __init__(self, scale, tfm, texname, vf):
     if six.PY3 and isinstance(texname, bytes):
         texname = texname.decode('ascii')
     self._scale, self._tfm, self.texname, self._vf = \
         scale, tfm, texname, vf
     self.size = scale * (72.0 / (72.27 * 2**16))
     try:
         nchars = max(six.iterkeys(tfm.width)) + 1
     except ValueError:
         nchars = 0
     self.widths = [(1000 * tfm.width.get(char, 0)) >> 20
                    for char in xrange(nchars)]
Beispiel #40
0
def test_figure():
    # named figure support
    fig = plt.figure('today')
    ax = fig.add_subplot(111)
    ax.set_title(fig.get_label())
    ax.plot(list(xrange(5)))
    # plot red line in a different figure.
    plt.figure('tomorrow')
    plt.plot([0, 1], [1, 0], 'r')
    # Return to the original; make sure the red line is not there.
    plt.figure('today')
    plt.close('tomorrow')
Beispiel #41
0
    def test_line_extents_for_non_affine_transData(self):
        ax = plt.axes(projection='polar')
        # add 10 to the radius of the data
        offset = mtrans.Affine2D().translate(0, 10)

        plt.plot(list(xrange(10)), transform=offset + ax.transData)
        # the data lim of a polar plot is stored in coordinates
        # before a transData transformation, hence the data limits
        # are not what is being shown on the actual plot.
        expeted_data_lim = np.array([[0., 0.], [9., 9.]]) + [0, 10]
        np.testing.assert_array_almost_equal(ax.dataLim.get_points(),
                                             expeted_data_lim)
Beispiel #42
0
    def __init__(self,  bysecond=None, interval=1, tz=None):
        """
        Mark every second in *bysecond*; *bysecond* can be an int or
        sequence.  Default is to tick every second: ``bysecond = range(60)``

        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second occurrence.

        """
        if bysecond is None:
            bysecond = list(xrange(60))
        rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)
        RRuleLocator.__init__(self, rule, tz)
Beispiel #43
0
    def __init__(self,  byhour=None, interval=1, tz=None):
        """
        Mark every hour in *byhour*; *byhour* can be an int or sequence.
        Default is to tick every hour: ``byhour=range(24)``

        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second occurrence.
        """
        if byhour is None:
            byhour = list(xrange(24))
        rule = rrulewrapper(HOURLY, byhour=byhour, interval=interval,
                            byminute=0, bysecond=0)
        RRuleLocator.__init__(self, rule, tz)
Beispiel #44
0
def plot_vo(tri, colors=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if colors is None:
        colors = [(0, 1, 0, 0.2)]
    lc = mpl.collections.LineCollection(np.array(
        [(tri.circumcenters[i], tri.circumcenters[j])
         for i in xrange(len(tri.circumcenters))
         for j in tri.triangle_neighbors[i] if j != -1]),
        colors=colors)
    ax = pl.gca()
    ax.add_collection(lc)
    pl.draw_if_interactive()
Beispiel #45
0
    def __init__(self,  bymonth=None, bymonthday=1, interval=1, tz=None):
        """
        Mark every month in *bymonth*; *bymonth* can be an int or
        sequence.  Default is ``range(1,13)``, i.e. every month.

        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second occurance.
        """
        if bymonth is None:
            bymonth = list(xrange(1, 13))
        o = rrulewrapper(MONTHLY, bymonth=bymonth, bymonthday=bymonthday,
                         interval=interval, **self.hms0d)
        RRuleLocator.__init__(self, o, tz)
Beispiel #46
0
    def __init__(self, bysecond=None, interval=1, tz=None):
        """
        Mark every second in *bysecond*; *bysecond* can be an int or
        sequence.  Default is to tick every second: ``bysecond = range(60)``

        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second occurrence.

        """
        if bysecond is None:
            bysecond = list(xrange(60))
        rule = rrulewrapper(SECONDLY, bysecond=bysecond, interval=interval)
        RRuleLocator.__init__(self, rule, tz)
Beispiel #47
0
    def __init__(self, bymonthday=None, interval=1, tz=None):
        """
        Mark every day in *bymonthday*; *bymonthday* can be an int or
        sequence.

        Default is to tick every day of the month: ``bymonthday=range(1,32)``
        """
        if bymonthday is None:
            bymonthday = list(xrange(1, 32))
        o = rrulewrapper(DAILY,
                         bymonthday=bymonthday,
                         interval=interval,
                         **self.hms0d)
        RRuleLocator.__init__(self, o, tz)
Beispiel #48
0
def test_external_transform_api():
    class ScaledBy(object):
        def __init__(self, scale_factor):
            self._scale_factor = scale_factor

        def _as_mpl_transform(self, axes):
            return mtrans.Affine2D().scale(self._scale_factor) + axes.transData

    ax = plt.axes()
    line, = plt.plot(list(xrange(10)), transform=ScaledBy(10))
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    # assert that the top transform of the line is the scale transform.
    np.testing.assert_allclose(line.get_transform()._a.get_matrix(), mtrans.Affine2D().scale(10).get_matrix())
Beispiel #49
0
    def __init__(self,
                 fig,
                 func,
                 frames=None,
                 init_func=None,
                 fargs=None,
                 save_count=None,
                 **kwargs):
        if fargs:
            self._args = fargs
        else:
            self._args = ()
        self._func = func

        # Amount of framedata to keep around for saving movies. This is only
        # used if we don't know how many frames there will be: in the case
        # of no generator or in the case of a callable.
        self.save_count = save_count

        # Set up a function that creates a new iterable when needed. If nothing
        # is passed in for frames, just use itertools.count, which will just
        # keep counting from 0. A callable passed in for frames is assumed to
        # be a generator. An iterable will be used as is, and anything else
        # will be treated as a number of frames.
        if frames is None:
            self._iter_gen = itertools.count
        elif six.callable(frames):
            self._iter_gen = frames
        elif iterable(frames):
            self._iter_gen = lambda: iter(frames)
            if hasattr(frames, '__len__'):
                self.save_count = len(frames)
        else:
            self._iter_gen = lambda: xrange(frames).__iter__()
            self.save_count = frames

        # If we're passed in and using the default, set it to 100.
        if self.save_count is None:
            self.save_count = 100

        self._init_func = init_func

        # Needs to be initialized so the draw functions work without checking
        self._save_seq = []

        TimedAnimation.__init__(self, fig, **kwargs)

        # Need to reset the saved seq, since right now it will contain data
        # for a single frame from init, which is not what we want.
        self._save_seq = []
Beispiel #50
0
    def decorate(method):
        get_args = [_arg_mapping[x] for x in args]

        @wraps(method)
        def wrapper(self, byte):
            if state is not None and self.state != state:
                raise ValueError("state precondition failed")
            return method(self, *[f(self, byte-min) for f in get_args])
        if max is None:
            table[min] = wrapper
        else:
            for i in xrange(min, max+1):
                assert table[i] is None
                table[i] = wrapper
        return wrapper
Beispiel #51
0
def plot_cc(tri, edgecolor=None):
    import matplotlib as mpl
    from matplotlib import pylab as pl
    if edgecolor is None:
        edgecolor = (0, 0, 1, 0.2)
    dxy = (np.array([(tri.x[i], tri.y[i]) for i, j, k in tri.triangle_nodes])
        - tri.circumcenters)
    r = np.hypot(dxy[:, 0], dxy[:, 1])
    ax = pl.gca()
    for i in xrange(len(r)):
        p = mpl.patches.Circle(tri.circumcenters[i], r[i],
                               resolution=100, edgecolor=edgecolor,
                               facecolor=(1, 1, 1, 0), linewidth=0.2)
        ax.add_patch(p)
    pl.draw_if_interactive()
Beispiel #52
0
def test_external_transform_api():
    class ScaledBy(object):
        def __init__(self, scale_factor):
            self._scale_factor = scale_factor

        def _as_mpl_transform(self, axes):
            return mtrans.Affine2D().scale(self._scale_factor) + axes.transData

    ax = plt.axes()
    line, = plt.plot(list(xrange(10)), transform=ScaledBy(10))
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 100)
    # assert that the top transform of the line is the scale transform.
    np.testing.assert_allclose(line.get_transform()._a.get_matrix(),
                               mtrans.Affine2D().scale(10).get_matrix())
def test_bbox_inches_tight_suptile_legend():
    plt.plot(list(xrange(10)), label='a straight line')
    plt.legend(bbox_to_anchor=(0.9, 1), loc=2, )
    plt.title('Axis title')
    plt.suptitle('Figure title')

    # put an extra long y tick on to see that the bbox is accounted for
    def y_formatter(y, pos):
        if int(y) == 4:
            return 'The number 4'
        else:
            return str(y)
    plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter))

    plt.xlabel('X axis')
Beispiel #54
0
def test_bbox_inches_tight_suptile_legend():
    plt.plot(list(xrange(10)), label='a straight line')
    plt.legend(bbox_to_anchor=(0.9, 1), loc=2, )
    plt.title('Axis title')
    plt.suptitle('Figure title')

    # put an extra long y tick on to see that the bbox is accounted for
    def y_formatter(y, pos):
        if int(y) == 4:
            return 'The number 4'
        else:
            return str(y)
    plt.gca().yaxis.set_major_formatter(FuncFormatter(y_formatter))

    plt.xlabel('X axis')
Beispiel #55
0
    def __init__(self, byhour=None, interval=1, tz=None):
        """
        Mark every hour in *byhour*; *byhour* can be an int or sequence.
        Default is to tick every hour: ``byhour=range(24)``

        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second occurrence.
        """
        if byhour is None:
            byhour = list(xrange(24))
        rule = rrulewrapper(HOURLY,
                            byhour=byhour,
                            interval=interval,
                            byminute=0,
                            bysecond=0)
        RRuleLocator.__init__(self, rule, tz)
Beispiel #56
0
    def __init__(self, bymonth=None, bymonthday=1, interval=1, tz=None):
        """
        Mark every month in *bymonth*; *bymonth* can be an int or
        sequence.  Default is ``range(1,13)``, i.e. every month.

        *interval* is the interval between each iteration.  For
        example, if ``interval=2``, mark every second occurance.
        """
        if bymonth is None:
            bymonth = list(xrange(1, 13))
        o = rrulewrapper(MONTHLY,
                         bymonth=bymonth,
                         bymonthday=bymonthday,
                         interval=interval,
                         **self.hms0d)
        RRuleLocator.__init__(self, o, tz)
Beispiel #57
0
def test_non_affine_caching():
    class AssertingNonAffineTransform(mtrans.Transform):
        """
        This transform raises an assertion error when called when it
        shouldn't be and self.raise_on_transform is True.

        """
        input_dims = output_dims = 2
        is_affine = False

        def __init__(self, *args, **kwargs):
            mtrans.Transform.__init__(self, *args, **kwargs)
            self.raise_on_transform = False
            self.underlying_transform = mtrans.Affine2D().scale(10, 10)

        def transform_path_non_affine(self, path):
            if self.raise_on_transform:
                assert False, ('Invalidated affine part of transform '
                               'unnecessarily.')
            return self.underlying_transform.transform_path(path)

        transform_path = transform_path_non_affine

        def transform_non_affine(self, path):
            if self.raise_on_transform:
                assert False, ('Invalidated affine part of transform '
                               'unnecessarily.')
            return self.underlying_transform.transform(path)

        transform = transform_non_affine

    my_trans = AssertingNonAffineTransform()
    ax = plt.axes()
    plt.plot(list(xrange(10)), transform=my_trans + ax.transData)
    plt.draw()
    # enable the transform to raise an exception if it's non-affine transform
    # method is triggered again.
    my_trans.raise_on_transform = True
    ax.transAxes.invalidate()
    plt.draw()