python类Line2D()的实例源码

draw_convnet.py 文件源码 项目:draw_convnet 作者: gwding 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def add_mapping(patches, colors, start_ratio, end_ratio, patch_size, ind_bgn,
                top_left_list, loc_diff_list, num_show_list, size_list):

    start_loc = top_left_list[ind_bgn] \
        + (num_show_list[ind_bgn] - 1) * np.array(loc_diff_list[ind_bgn]) \
        + np.array([start_ratio[0] * (size_list[ind_bgn][1] - patch_size[1]),
                    - start_ratio[1] * (size_list[ind_bgn][0] - patch_size[0])]
                   )




    end_loc = top_left_list[ind_bgn + 1] \
        + (num_show_list[ind_bgn + 1] - 1) * np.array(
            loc_diff_list[ind_bgn + 1]) \
        + np.array([end_ratio[0] * size_list[ind_bgn + 1][1],
                    - end_ratio[1] * size_list[ind_bgn + 1][0]])


    patches.append(Rectangle(start_loc, patch_size[1], -patch_size[0]))
    colors.append(Dark)
    patches.append(Line2D([start_loc[0], end_loc[0]],
                          [start_loc[1], end_loc[1]]))
    colors.append(Darker)
    patches.append(Line2D([start_loc[0] + patch_size[1], end_loc[0]],
                          [start_loc[1], end_loc[1]]))
    colors.append(Darker)
    patches.append(Line2D([start_loc[0], end_loc[0]],
                          [start_loc[1] - patch_size[0], end_loc[1]]))
    colors.append(Darker)
    patches.append(Line2D([start_loc[0] + patch_size[1], end_loc[0]],
                          [start_loc[1] - patch_size[0], end_loc[1]]))
    colors.append(Darker)
animate_entity_nodes.py 文件源码 项目:finite-element-course 作者: finite-element 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def redraw(self, origin, scale):
        for node in self.nodes:
            if isinstance(node, Annotation):
                node.xy = self.tr(node.xy, origin, scale)
                if hasattr(node, "xyann"):
                    node.xyann = self.tr(node.xyann, origin, scale)
            elif isinstance(node, Line2D):
                newpos = self.tr(node.get_xydata(), origin, scale)
                node.set_xdata(newpos[:, 0])
                node.set_ydata(newpos[:, 1])
            else:
                raise TypeError("Don't know how to morph : %s" % node)
        self.origin = origin
        self.scale = scale
animate_entity_nodes.py 文件源码 项目:finite-element-course 作者: finite-element 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def redraw(self, origin, scale):
        for node in self.nodes:
            if isinstance(node, Annotation):
                node.xy = self.tr(node.xy, origin, scale)
                if hasattr(node, "xyann"):
                    node.xyann = self.tr(node.xyann, origin, scale)
            elif isinstance(node, Line2D):
                newpos = self.tr(node.get_xydata(), origin, scale)
                node.set_xdata(newpos[:, 0])
                node.set_ydata(newpos[:, 1])
            else:
                raise TypeError("Don't know how to morph : %s" % node)
        self.origin = origin
        self.scale = scale
processData.py 文件源码 项目:anime_recs 作者: Cpierse 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def plot_top_sims(cos_sim_mat,aids,N_recs,aid_counts,aid_dict,
                  img_name = 'results\\Sample_similarities.png',threshold=0, 
                  main_name = None, var_name = 'Sim',
                  plot_histograms=True):
    ''' Plot of anime with the highest similarity scores. '''
    plt.figure(figsize=(6, 10))
    f, axarr = plt.subplots(len(aids),N_recs+1)
    f.set_size_inches(6, 10)
    f.tight_layout()
    for (idx_0,aid) in enumerate(aids):
        image = get_image(aid_dict[aid])
        axarr[idx_0,0].imshow(image)
        axarr[idx_0,0].axis("off")
        axarr[idx_0,0].set_title('Query ' + str(idx_0+1),size=10)
        top_aids,top_sims = get_highest_cos(cos_sim_mat,aid,aid_dict,N_recs,aid_counts,threshold)
        for (idx_1,aid_1) in enumerate(top_aids):
            image = get_image(aid_dict[aid_1])
            if image != None:
                axarr[idx_0,idx_1+1].imshow(image)
            axarr[idx_0,idx_1+1].axis("off")
            axarr[idx_0,idx_1+1].set_title(var_name + ' = {:.2f}'.format(top_sims[idx_1]),size=10)
        # Add horizonatal lines:
        if not idx_0==0 or idx_0==len(aids):
            line = lines.Line2D((0,1),(1-1.0/len(aids)*idx_0*0.98,1-1.0/len(aids)*idx_0*0.98), transform=f.transFigure,color=[0,0,0])
            f.lines.append(line)
            # TODO: the 0.98 shouldn't be necessary. Fixit. 
    if main_name:
        plt.suptitle(main_name)
    #plt.savefig(img_name,dpi=300,format='png')
    plt.show()
    # Plot a histrogram of these similarities:
    if plot_histograms:
        for aid in aids:
            plt.hist(cos_sim_mat[aid,:])
            plt.show()
    return None
Graph.py 文件源码 项目:TMV3 作者: HenricusRex 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __init__(self, ax, x, y, col, parent):
        self.parent = parent
        self.removed = False
        self.x = x
        self.y = y
        _xlim = ax.get_xlim()
        _ylim = ax.get_ylim()
        self.line1 = Line2D(_xlim, (y,y), picker=5)
        self.line2 = Line2D((x,x), _ylim, picker=5)
        self.line1.set_color(col)
        self.line2.set_color(col)
        ax.add_line(self.line1)
        ax.add_line(self.line2)
        parent.signalGraphUpdate.emit()
Graph.py 文件源码 项目:TMV3 作者: HenricusRex 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def toggleCursor(self):
        print('toggleCursor')


        if self.cursorActive:
            inv = self.host.transData.inverted()

            _xlim = self.host.get_xlim()
            _ylim = self.host.get_ylim()
            _xy1 = self.host.transData.transform((_xlim[0],_ylim[1]))
            _xy2 = self.host.transData.transform((_xlim[1],_ylim[0]))
            #_xy1 = self.host.transData.transform((_posx[0],_posy[0]))
            #ä_xy2 = self.host.transData.transform((_posx[1],_posy[1]))

            _x1 = _xy1[0]+20
            _x2 = _xy1[0]+40
            _y1 = _xy2[1]+20
            _y2 = _xy2[1]+40

            _xy1t = inv.transform((_x1,_y1))
            _xy2t = inv.transform((_x2,_y2))
            self.cursorA = CursorStatic(self.host,_xy1t[0],_xy1t[1],'gray',self)
            self.cursorB = CursorStatic(self.host,_xy2t[0],_xy2t[1],'black',self)
            self.showCursorPos(self.cursorA.x,self.cursorA.y,'A')
            self.showCursorPos(self.cursorB.x,self.cursorB.y,'B')
            self.showCursorPos(math.fabs(self.cursorB.x-self.cursorA.x),math.fabs(self.cursorB.y-self.cursorA.y),'C')
            # # self.line = Line2D(_xy1,_xy2)

            # self.line1 = Line2D(_xlim, (_xy2t[1],_xy2t[1]))
            # self.line2 = Line2D((_xy1t[0],_xy1t[0]), _ylim)
            # self.host.add_line(self.line1)
            # self.host.add_line(self.line2)
            # self.signalGraphUpdate.emit()
            print ('cursor added')
#           self.cursorD = Cursor(self.host, useblit=False, color='blue', linewidth=2)
        else:
            self.cursorA.delLine()
            self.cursorA = None
            self.cursorB.delLine()
            self.cursorB = None
interactive_plot.py 文件源码 项目:pizza_math 作者: NicholasARossi 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, points, line, linedata):
        if isinstance(points, matplotlib.lines.Line2D):
            suffix = "pts"
        else:
            suffix = None

        self.dict_ = {"type": "linkedview",
                      "idpts": utils.get_id(points, suffix),
                      "idline": utils.get_id(line),
                      "data": linedata}
evoked.py 文件源码 项目:decoding_challenge_cortana_2016_3rd 作者: kingjr 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def _connection_line(x, fig, sourceax, targetax):
    """Helper function to connect time series and topolots"""
    from matplotlib.lines import Line2D
    transFigure = fig.transFigure.inverted()
    tf = fig.transFigure

    (xt, yt) = transFigure.transform(targetax.transAxes.transform([.5, .25]))
    (xs, _) = transFigure.transform(sourceax.transData.transform([x, 0]))
    (_, ys) = transFigure.transform(sourceax.transAxes.transform([0, 1]))
    return Line2D((xt, xs), (yt, ys), transform=tf, color='grey',
                  linestyle='-', linewidth=1.5, alpha=.66, zorder=0)
plot.py 文件源码 项目:psst 作者: power-system-simulation-toolbox 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def plot_costs(case, number_of_segments=1, ax=None, legend=True):
    if ax is None:
        fig, axs = plt.subplots(1, 1, figsize=(16, 10))
        ax = axs

    color_scale = make_interpolater(0, len(case.gen_name), 0, 1)

    color = {g: plt.cm.jet(color_scale(i)) for i, g in enumerate(case.gen_name)}

    for s in calculate_segments(case, number_of_segments=number_of_segments):
        pmin, pmax = s['segment']
        x = np.linspace(pmin, pmax)
        y = x * s['slope']
        ax.plot(x, y, color=color[s['name']])

    ax = ax.twinx()
    for s in calculate_segments(case, number_of_segments=number_of_segments):
        pmin, pmax = s['segment']
        x = np.linspace(pmin, pmax)
        y = [s['slope'] for _ in x]
        ax.plot(x, y, color=color[s['name']])

    ax.set_ylim(0, 1.2*y[-1])

    if legend:
        lines = list()
        for g in case.gen_name:
            lines.append(mlines.Line2D([], [], color=color[g], label=g))
            ax.legend(handles=lines, loc='upper left')

    return ax
geom_boxplot.py 文件源码 项目:plotnine 作者: has2k1 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def draw_legend(data, da, lyr):
        """
        Draw a rectangle in the box

        Parameters
        ----------
        data : dataframe
        da : DrawingArea
        lyr : layer

        Returns
        -------
        out : DrawingArea
        """
        data['size'] *= SIZE_FACTOR

        # box
        facecolor = to_rgba(data['fill'], data['alpha'])
        if facecolor is None:
            facecolor = 'none'

        kwargs = dict(
           linestyle=data['linetype'],
           linewidth=data['size'])

        box = Rectangle((da.width*.125, da.height*.25),
                        width=da.width*.75,
                        height=da.height*.5,
                        facecolor=facecolor,
                        edgecolor=data['color'],
                        capstyle='projecting',
                        antialiased=False,
                        **kwargs)
        da.add_artist(box)

        kwargs['solid_capstyle'] = 'butt'
        kwargs['color'] = data['color']
        # middle strike through
        strike = mlines.Line2D([da.width*.125, da.width*.875],
                               [da.height*.5, da.height*.5],
                               **kwargs)
        da.add_artist(strike)

        # whiskers
        top = mlines.Line2D([da.width*.5, da.width*.5],
                            [da.height*.75, da.height*.9],
                            **kwargs)
        da.add_artist(top)

        bottom = mlines.Line2D([da.width*.5, da.width*.5],
                               [da.height*.25, da.height*.1],
                               **kwargs)
        da.add_artist(bottom)
        return da
plot.py 文件源码 项目:BAG_framework 作者: ucb-art 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def on_pick(self, event):
        artist = event.artist
        if not artist.get_visible():
            return
        for idx, artist_set in enumerate(self.pick_sets):
            if artist in artist_set:
                self.pick_funs[idx](artist)
                return

        if isinstance(artist, Line2D):
            mevent = event.mouseevent
            # figure out if we picked marker or line
            self.drag_idx = self._get_idx_under_point(mevent)

            if self.drag_idx >= 0:
                # picked marker.
                ax = mevent.inaxes
                an, pt, _, _ = self.markers[self.drag_idx]
                an.set_visible(False)
                pt.set_visible(False)
                self.canvas.draw()
                self.markers[self.drag_idx][-1] = self.canvas.copy_from_bbox(ax.bbox)
                an.set_visible(True)
                pt.set_visible(True)
                ax.draw_artist(an)
                ax.draw_artist(pt)
                self.canvas.blit(ax.bbox)

            else:
                # save data to plot marker later
                mxval = mevent.xdata
                button = mevent.button
                if mxval is not None and button == 1 and not self.marker_line_info:
                    self.marker_line_info = (artist, mxval, mevent.ydata,
                                             button, mevent.inaxes)
        elif isinstance(artist, Annotation):
            # delete marker.
            mevent = event.mouseevent
            if mevent.button == 3:
                targ_idx = None
                for idx, (an, pt, _, _) in enumerate(self.markers):
                    if an is artist:
                        targ_idx = idx
                        break
                if targ_idx is not None:
                    an, pt, _, _ = self.markers[targ_idx]
                    del self.markers[targ_idx]
                    an.set_visible(False)
                    pt.set_visible(False)
                    self.canvas.draw()
test_graphics.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def _check_colors(self, collections, linecolors=None, facecolors=None,
                      mapping=None):
        """
        Check each artist has expected line colors and face colors

        Parameters
        ----------
        collections : list-like
            list or collection of target artist
        linecolors : list-like which has the same length as collections
            list of expected line colors
        facecolors : list-like which has the same length as collections
            list of expected face colors
        mapping : Series
            Series used for color grouping key
            used for andrew_curves, parallel_coordinates, radviz test
        """

        from matplotlib.lines import Line2D
        from matplotlib.collections import Collection, PolyCollection
        conv = self.colorconverter
        if linecolors is not None:

            if mapping is not None:
                linecolors = self._get_colors_mapped(mapping, linecolors)
                linecolors = linecolors[:len(collections)]

            self.assertEqual(len(collections), len(linecolors))
            for patch, color in zip(collections, linecolors):
                if isinstance(patch, Line2D):
                    result = patch.get_color()
                    # Line2D may contains string color expression
                    result = conv.to_rgba(result)
                elif isinstance(patch, PolyCollection):
                    result = tuple(patch.get_edgecolor()[0])
                else:
                    result = patch.get_edgecolor()

                expected = conv.to_rgba(color)
                self.assertEqual(result, expected)

        if facecolors is not None:

            if mapping is not None:
                facecolors = self._get_colors_mapped(mapping, facecolors)
                facecolors = facecolors[:len(collections)]

            self.assertEqual(len(collections), len(facecolors))
            for patch, color in zip(collections, facecolors):
                if isinstance(patch, Collection):
                    # returned as list of np.array
                    result = patch.get_facecolor()[0]
                else:
                    result = patch.get_facecolor()

                if isinstance(result, np.ndarray):
                    result = tuple(result)

                expected = conv.to_rgba(color)
                self.assertEqual(result, expected)
test_graphics.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_area_colors(self):
        from matplotlib import cm
        from matplotlib.collections import PolyCollection

        custom_colors = 'rgcby'
        df = DataFrame(rand(5, 5))

        ax = df.plot.area(color=custom_colors)
        self._check_colors(ax.get_lines(), linecolors=custom_colors)
        poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
        self._check_colors(poly, facecolors=custom_colors)

        handles, labels = ax.get_legend_handles_labels()
        # legend is stored as Line2D, thus check linecolors
        linehandles = [x for x in handles if not isinstance(x, PolyCollection)]
        self._check_colors(linehandles, linecolors=custom_colors)
        for h in handles:
            self.assertTrue(h.get_alpha() is None)
        tm.close()

        ax = df.plot.area(colormap='jet')
        jet_colors = lmap(cm.jet, np.linspace(0, 1, len(df)))
        self._check_colors(ax.get_lines(), linecolors=jet_colors)
        poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
        self._check_colors(poly, facecolors=jet_colors)

        handles, labels = ax.get_legend_handles_labels()
        linehandles = [x for x in handles if not isinstance(x, PolyCollection)]
        self._check_colors(linehandles, linecolors=jet_colors)
        for h in handles:
            self.assertTrue(h.get_alpha() is None)
        tm.close()

        # When stacked=False, alpha is set to 0.5
        ax = df.plot.area(colormap=cm.jet, stacked=False)
        self._check_colors(ax.get_lines(), linecolors=jet_colors)
        poly = [o for o in ax.get_children() if isinstance(o, PolyCollection)]
        jet_with_alpha = [(c[0], c[1], c[2], 0.5) for c in jet_colors]
        self._check_colors(poly, facecolors=jet_with_alpha)

        handles, labels = ax.get_legend_handles_labels()
        # Line2D can't have alpha in its linecolor
        self._check_colors(handles[:len(jet_colors)], linecolors=jet_colors)
        for h in handles:
            self.assertEqual(h.get_alpha(), 0.5)
plot_dual.py 文件源码 项目:xbox-controller-plot 作者: cookacounty 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def __init__(self):
        fig = plt.figure(figsize=(10,4))
        a1_z   = fig.add_subplot(1, 11, 1)
        a1_xy = fig.add_subplot(1, 11, (2, 6))
        a2_z   = fig.add_subplot(1, 11, 7)
        a2_xy = fig.add_subplot(1, 11, (8, 12))
        plt.tight_layout()
        fig.suptitle("3D Sensor and Xbox Controller Demo", fontsize=18)


        plt.setp(a1_z.get_xticklabels(), visible=False)
        plt.setp(a2_z.get_xticklabels(), visible=False)


        a1_z.set_title('3D Sensor Z')
        a2_z.set_title('Xbox L Z')

        a1_xy.set_title('3D Sensor XY')
        a2_xy.set_title('Xbox L XY')

        # Joy 1 Z
        a1_z.set_ylabel('z')
        self.line_z1 = Line2D([], [], color='blue', linewidth=20)
        a1_z.add_line(self.line_z1)
        a1_z.set_xlim(-1, 1)
        a1_z.set_ylim(-1, 1)

        # Joy 1 XY
        a1_xy.set_xlabel('x')
        a1_xy.set_ylabel('y')
        self.line_xy1 = Line2D([], [], color='green', linewidth=3)
        a1_xy.add_line(self.line_xy1)
        a1_xy.set_xlim(-1, 1)
        a1_xy.set_ylim(-1, 1)

        # Joy 2 Z
        a2_z.set_ylabel('z')
        self.line_z2 = Line2D([], [], color='blue', linewidth=20)
        a2_z.add_line(self.line_z2)
        a2_z.set_xlim(-1, 1)
        a2_z.set_ylim(0, 1)
        # Joy 2 XY
        a2_xy.set_xlabel('x')
        a2_xy.set_ylabel('y')
        self.line_xy2 = Line2D([], [], color='green', linewidth=3)
        a2_xy.add_line(self.line_xy2)
        a2_xy.set_xlim(-1, 1)
        a2_xy.set_ylim(-1, 1)

        animation.TimedAnimation.__init__(self, fig, interval=50, blit=True)
demo_subplot.py 文件源码 项目:xbox-controller-plot 作者: cookacounty 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self):
        fig = plt.figure()
        ax1 = fig.add_subplot(1, 6, (1, 2))
        ax2 = fig.add_subplot(1, 6, (3, 4))
        ax3 = fig.add_subplot(1, 6, 5)

        self.t = np.linspace(0, 80, 400)
        self.x = np.cos(2 * np.pi * self.t / 10.)
        self.y = np.sin(2 * np.pi * self.t / 10.)
        self.z = 10 * self.t

        ax1.set_xlabel('x')
        ax1.set_ylabel('y')
        self.line1 = Line2D([], [], color='black')
        self.line1a = Line2D([], [], color='red', linewidth=2)
        self.line1e = Line2D(
            [], [], color='red', marker='o', markeredgecolor='r')
        ax1.add_line(self.line1)
        ax1.add_line(self.line1a)
        ax1.add_line(self.line1e)
        ax1.set_xlim(-1, 1)
        ax1.set_ylim(-2, 2)
        ax1.set_aspect('equal', 'datalim')

        ax2.set_xlabel('y')
        ax2.set_ylabel('z')
        self.line2 = Line2D([], [], color='black')
        self.line2a = Line2D([], [], color='red', linewidth=2)
        self.line2e = Line2D(
            [], [], color='red', marker='o', markeredgecolor='r')
        ax2.add_line(self.line2)
        ax2.add_line(self.line2a)
        ax2.add_line(self.line2e)
        ax2.set_xlim(-1, 1)
        ax2.set_ylim(0, 800)

        ax3.set_xlabel('x')
        ax3.set_ylabel('z')
        self.line3 = Line2D([], [], color='black')
        self.line3a = Line2D([], [], color='red', linewidth=2)
        self.line3e = Line2D(
            [], [], color='red', marker='o', markeredgecolor='r')
        ax3.add_line(self.line3)
        ax3.add_line(self.line3a)
        ax3.add_line(self.line3e)
        ax3.set_xlim(-1, 1)
        ax3.set_ylim(0, 800)

        animation.TimedAnimation.__init__(self, fig, interval=50, blit=True)
lambdamart.py 文件源码 项目:rankpy 作者: dmitru 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def plot_lambdas_parallel_coordinates(lambdas, relevance_scores, individual=False, cumulative=False):
    unique_scores = sorted(np.unique(relevance_scores).astype(int), reverse=True)
    colors = ['r', 'g', 'b', 'y', 'c', 'm', 'y', 'k']

    if not individual:
        plt.figure()

        legend_handles = []
        legend_labels = []

        for c, r in enumerate(unique_scores):
            legend_handles.append(mlines.Line2D([], [], color=colors[c], linewidth=2))
            legend_labels.append('Relevance %d' % r)

    if cumulative:
        lambdas_cumsum = lambdas.cumsum(axis=0)
        ymin, ymax = lambdas_cumsum.min(), lambdas_cumsum.max()
    else:
        ymin, ymax = lambdas.min(), lambdas.max()

    for c, r in enumerate(unique_scores):
        if individual:
            plt.figure()

        if cumulative:
            plt.plot(lambdas[:, relevance_scores == r].cumsum(axis=0), '-', marker='.', markersize=1, c=colors[c], alpha=0.4)
        else:
            plt.plot(lambdas[:, relevance_scores == r], '-', marker='.', markersize=1, c=colors[c], alpha=0.4)

        if individual:
            plt.gca().get_xaxis().set_major_locator(MaxNLocator(integer=True))
            plt.gca().set_ylim([ymin, ymax])

            plt.title('Paralell Coordinates for%sLambdas (Relevance %d)' % (' Cumulative ' if cumulative else ' ', r))
            plt.xlabel('Trees')
            plt.ylabel('Cumulative Lambda Values' if cumulative else 'Lambda Values')
            plt.show()

    if not individual:
        plt.gca().get_yaxis().set_major_locator(MaxNLocator(integer=True))
        plt.gca().set_ylim([ymin, ymax])

        plt.title('Paralell Coordinates for%sLambdas (Relevance %d)' % (' Cumulative ' if cumulative else ' ', r))
        plt.xlabel('Trees')
        plt.ylabel('Cumulative Lambda Values' if cumulative else 'Lambda Values')    

        plt.legend(legend_handles, legend_labels, loc='best')
        plt.show()
util.py 文件源码 项目:ib_insync 作者: erdewit 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def barplot(bars, title='', upColor='blue', downColor='red'):
    """
    Create candlestick plot for the given bars. The bars can be given as
    a DataFrame or as a list of bar objects.
    """
    import pandas as pd
    import matplotlib.pyplot as plt
    from matplotlib.lines import Line2D
    from matplotlib.patches import Rectangle

    if isinstance(bars, pd.DataFrame):
        ohlcTups = [tuple(v) for v in
                bars[['open', 'high', 'low', 'close']].values]
    else:
        ohlcTups = [(b.open, b.high, b.low, b.close) for b in bars]

    fig, ax = plt.subplots()
    ax.set_title(title)
    ax.grid(True)
    fig.set_size_inches(10, 6)
    for n, (open_, high, low, close) in enumerate(ohlcTups):
        if close >= open_:
            color = upColor
            bodyHi, bodyLo = close, open_
        else:
            color = downColor
            bodyHi, bodyLo = open_, close
        line = Line2D(
                xdata=(n, n),
                ydata=(low, bodyLo),
                color=color,
                linewidth=1)
        ax.add_line(line)
        line = Line2D(
                xdata=(n, n),
                ydata=(high, bodyHi),
                color=color,
                linewidth=1)
        ax.add_line(line)
        rect = Rectangle(
                xy=(n - 0.3, bodyLo),
                width=0.6,
                height=bodyHi - bodyLo,
                edgecolor=color,
                facecolor=color,
                alpha=0.4,
                antialiased=True
        )
        ax.add_patch(rect)

    ax.autoscale_view()
    return fig
plots.py 文件源码 项目:Smart-Meter-Experiment-ML-Revisited 作者: felgueres 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def plot_behavior_cluster(centroids, num_clusters):
    '''
    Plots computed clusters.

    Parameters
    ----------

    Centroids : array
        Predicted centroids of clusters.

    num_clusters: int
        Number of clusters.

    Returns
    -------

    Plot : matplotlib.lines.Line2D
        Figure.

    '''

    # Figure has all clusters on same plot.

    fig = plt.figure(figsize=(10,7))
    ax = fig.add_subplot(1,1,1)

    # Set colors.
    colors = cm.rainbow(np.linspace(0, 1, num_clusters))

    # Plot cluster and corresponding color.
    for cluster, color in enumerate(colors, start =1):

        ax.plot(centroids[cluster-1], c = color, label = "Cluster %d" % cluster)

    # Format figure.
    ax.set_title("Centroids of consumption pattern of clusters, where k = %d" % num_clusters, fontsize =14, fontweight='bold')
    ax.set_xlim([0, 24])
    ax.set_xticks(range(0, 25, 6))
    ax.set_xlabel("Time (h)")
    ax.set_ylabel("Consumption (kWh)")
    leg = plt.legend(frameon = True, loc = 'upper left', ncol =2, fontsize = 12)
    leg.get_frame().set_edgecolor('b')

    plt.show()
plots.py 文件源码 项目:Smart-Meter-Experiment-ML-Revisited 作者: felgueres 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def plot_cluster_hist(X_featurized, labels, num_clusters):
    '''
    Plot histograms of users and corresponding clusters.

    Parameters
    ----------

    X_featurized : array-like
        Featurized Data

    labels: array-like
        Predicted cluster to data.

    num_clusters: int
        Number of clusters.

    Returns
    -------

    Plot : matplotlib.lines.Line2D
        Figure.

    '''

    fig = plt.figure()
    ax_ = fig.add_subplot(1,1,1)

    # Set colors.
    # Create DataFrame with features and labels.
    # Note sklearn cluster naming starts at zero, so adding 1 is convenient.

    X_featurized['label'] = labels + 1
    # Parameters for plotting.
    params_ = {'ax': ax_ , 'bins': np.arange(num_clusters +2) - 0.5}
    # Plot cluster and corresponding color.
    X_featurized.label.plot(kind = 'hist', **params_)

    # Format figure.

    ax_.set_title("Number of users in each cluster.", fontsize =14, fontweight='bold')
    ax_.set_xticks(range(1, num_clusters +1))
    ax_.set_xlim([0, num_clusters + 1])
    ax_.set_ylim([0,1200])
    ax_.set_xlabel('Cluster')
    ax_.set_ylabel("Number of users")

    # plt.savefig('cluster_hist')
    plt.show()


问题


面经


文章

微信
公众号

扫码关注公众号