コード例 #1
0
    def test_plot_bars_align_left(self):
        actual = visualize.plot_bars(x=[1, 2], heights=[1, 2], label="yo", hatch="/")

        expected = [
            plt.Rectangle(
                # if align == "center":
                #     rect_xmin = xpt - half_width
                #     rect_xmax = xpt + half_width
                xy=(
                    1,
                    0,
                ),
                height=1,
                width=0.8,  # width = diff * 0.8
                alpha=0.8,
                label="yo",
                hatch="/",
            ),
            plt.Rectangle(
                # if align == "center":
                #     rect_xmin = xpt - half_width
                #     rect_xmax = xpt + half_width
                xy=(
                    2,
                    0,
                ),
                height=2,
                width=0.8,  # width = diff * 0.8
                alpha=0.8,
                hatch="/",
            ),
        ]

        self._assert_matplotlib_rectangles_list(actual, expected)
コード例 #2
0
    def test_plot_bars_align_right(self):
        actual = visualize.plot_bars(
            x=[1, 2], heights=[1, 2], width=1, label="yo", hatch="/"
        )

        expected = [
            plt.Rectangle(
                xy=(
                    2,
                    0,
                ),
                height=1,
                width=1,
                alpha=0.8,
                label="yo",
                hatch="/",
            ),
            plt.Rectangle(
                xy=(
                    3,
                    0,
                ),
                height=2,
                width=1,
                alpha=0.8,
                hatch="/",
            ),
        ]

        self._assert_matplotlib_rectangles_list(actual, expected)
コード例 #3
0
 def psquare(self, x, y, col, full=False):
     if full:
         plt.gcf().gca().add_artist(
             plt.Rectangle((x, y), self.Size, self.Size, ec=col, color=col))
     else:
         plt.gcf().gca().add_artist(
             plt.Rectangle((x, y),
                           self.Size,
                           self.Size,
                           ec=col,
                           color='white'))
コード例 #4
0
ファイル: test.py プロジェクト: gmysage/pyqt_tomo
def line_select_callback(eclick, erelease):
    x1, y1 = eclick.xdata, eclick.ydata
    x2, y2 = erelease.xdata, erelease.ydata
    rect = plt.Rectangle((min(x1, x2), min(y1, y2)), np.abs(x1 - x2),
                         np.abs(y1 - y2))
    axes.add_patch(rect)
    print('efd')
コード例 #5
0
 def plot_aperture_images(self, stack=None, info=None, lines=None):
     if stack is None: stack = self.ap_stack
     WQB = WQStackBrowser(self.ap_stack, info, lines, aspect='auto')
     c = self.crop
     WQB.axis.add_patch(plt.Rectangle((c['xmin'],c['ymin']), \
       c['xmax']-c['xmin'],c['ymax']-c['ymin'],lw=3,ec='red',fc='0.5',alpha=0.2))
     return WQB
コード例 #6
0
ファイル: tree.py プロジェクト: Minyall/homer
    def draw(self, ax, center, bottom, highlight_words={}):
        if self.height is None or self.width is None or self.child_bottoms is None:
            self.compute_size()

        if self.is_leaf:
            if self.contents in highlight_words:
                self.text_properties['color'] = highlight_words[self.contents]
            else:
                self.text_properties['color'] = 'k'

            ax.text(center,
                    bottom,
                    self.contents,
                    transform=None,
                    **self.text_properties)
        else:
            [
                child.draw(ax, center, bottom + child_bottom,
                           highlight_words) for child, child_bottom in zip(
                               self.k_children, self.child_bottoms)
            ]
            ax.add_patch(
                plt.Rectangle((center - .5 * self.width, bottom),
                              self.width,
                              self.height - self.pts_buffer / 2,
                              alpha=.1,
                              transform=None))
        ax.set_axis_off()
コード例 #7
0
ファイル: plot_util.py プロジェクト: artemyk/chordsentiment
def wordshift_legend(ax, xoffset, yoffset, bwidth=1.05):
    lineheight = 0.09
    import matplotlib.transforms as transforms

    trans = transforms.blended_transform_factory(ax.transAxes, ax.transAxes)

    ax2 = plt.gcf().add_axes([0, 0, 1, 1])
    ax2.axis('off')
    ax2.xaxis.set_visible(False)
    ax2.yaxis.set_visible(False)
    ax2.set_zorder(1000)

    patch = plt.Rectangle((xoffset - 0.025, yoffset - 4 * lineheight),
                          bwidth,
                          4.5 * lineheight,
                          facecolor=[0.9, 0.9, 0.9],
                          edgecolor='k',
                          linewidth=LINEWIDTH,
                          transform=trans)
    ax2.add_patch(patch)

    txtprops = {'va': 'top', 'transform': trans, 'fontsize': 'small'}

    plt.text(xoffset, yoffset, u'+  High valence', color='orange', **txtprops)
    plt.text(xoffset,
             yoffset - 1 * lineheight,
             u' -  Low valence',
             color='blue',
             **txtprops)
    plt.text(xoffset, yoffset - 2 * lineheight, u'$↑$ Overexpressed',
             **txtprops)
    plt.text(xoffset, yoffset - 3 * lineheight, u'$↓$ Underexpressed',
             **txtprops)
コード例 #8
0
    def plot(self,circle=True,square=False,savefig=False,spath='../figs/eROSITA/'):
        """
        plot cluster image with radius and mass information
        """
        w_pix = self.w_pix
        mid_pix = self.mid_pix
        
        Rpixel = self.Rpixel
        cluster = self.image
        cluster_id = self.id

        plt.figure(figsize=(4,4))        
        cmap = plt.cm.rainbow
        cmap.set_under(color="white",alpha=0)

        agn_cmap = plt.cm.viridis
        agn_cmap.set_under(color="white",alpha=0)

        im = plt.imshow(np.log10(self.image),cmap=cmap,interpolation='none')
        #im = plt.imshow(np.log10(agn),cmap=agn_cmap,interpolation='none')

        ax = plt.gca()
        
        if self.meta is None:
            plt.title('Noise')
        else:
            
            cluster_row = self.meta
            log_m = np.log10(cluster_row['M500_msolh'])[0]
            plt.title(r'$\log\left(\frac{M_\mathrm{500c}}{h^{-1}\,M_\odot}\right) = $'+'{:.2f}'.format(log_m))
            
            if circle:
                circle = plt.Circle((self.xmid, self.ymid), self.Rpixel, color="red",fill=False,zorder=2000)
                ax.add_patch(circle)
        
            if square:
                circle = plt.Rectangle((self.xmid-384/2, self.ymid-384/2), 384, 384, color="black",fill=False,zorder=2000)
                ax.add_patch(circle)


        divider = make_axes_locatable(ax)
        cax = divider.append_axes("right", size="5%", pad=0.12)

        plt.colorbar(im, cax=cax)
        ax.set_xticks(np.arange(0,w_pix,100))
        ax.set_yticks(np.arange(0,w_pix,100))

        ax.set_xlabel("x"), ax.set_ylabel("y")
        ax.set_facecolor('white')
        
        plt.tight_layout()

        if savefig:
            plt.savefig('fpath' + file_name + '.png',dpi=250,bbox_inches='tight')

        ax.invert_yaxis()
        plt.show()

        plt.close()
        return None
コード例 #9
0
def draw_detection(img_path, label_path, savedir, num2label_map=None, label2num_map=None, absCoord=False):
    img = imread(img_path)
    h, w, c =  img.shape
    img_name =  get_image_name(img_path)
    bboxes = load_bboxes(label_path, w, h, num2label_map,absCoord)
    plt.clf()
    plt.imshow(img)
    plt.axis('off');
    ax = plt.gca()

    num_classes = len(num2label_map) if num2label_map else 15
    colors = plt.cm.hsv(np.linspace(0, 1, num_classes)).tolist()
    
    for obj in bboxes:
        
        label = obj['label']
        color_num = label2num_map[label] if label2num_map else int(label)
        color = colors[color_num % num_classes]
        
        bbox = obj['bbox']
        coords = (bbox[0] - bbox[2]/2., bbox[1]-bbox[3]/2.), bbox[2], bbox[3]
        ax.add_patch(plt.Rectangle(*coords, fill=False, edgecolor=color, linewidth=1))
        if 'score' in obj:
            score = obj['score']
            display_text = '%s: %.2f' % (label, score)
        else:
            display_text = str(label)
            ax.text(coords[0][0], coords[0][1], display_text, bbox={'facecolor':color, 'alpha':0.5})
    if savedir and bboxes:
        save_img = os.path.join(savedir, img_name)
        plt.savefig(save_img, bbox_inches="tight")
        print "saving image:%s" % save_img
コード例 #10
0
def plot_random_returns(df_price_oos, df_hard_returns, n=1000):
    returns_length = df_price_oos.shape[0]
    rand = np.random.random((n, returns_length))
    rand_yn = rand > .5
    rand_returns = rand_yn * df_price_oos.next_day_log_return.as_matrix()
    returns = np.exp(np.cumsum(rand_returns, axis=1))
    x = np.arange(rand_returns.shape[1])

    with sns.axes_style("whitegrid"):
        fig, ax = plt.subplots()
        np.exp(df_price_oos.log_return.cumsum()).plot(ax=ax, color="black")
        xlim = ax.get_xlim()
        x = np.linspace(xlim[0], xlim[1], rand_returns.shape[1])

        ps = []
        labels = []
        #p1 =
        #p2 = Rectangle((0, 0), 1, 1, fc="red")
        #legend([p1, p2], [a1_label, a2_label])

        for alpha, q in [(.10, 1), (.20, 5), (.30, 10), (.40, 20), (.50, 35)]:
            upper = np.percentile(returns, 100 - q, axis=0)
            lower = np.percentile(returns, q, axis=0)
            ps.append(plt.Rectangle((0, 0), 1, 1, fc="blue", alpha=alpha))
            labels.append("{} - {}".format(
                float(q) / 100, (100 - float(q)) / 100))
            ax.fill_between(x, upper, lower, alpha=alpha)
        np.exp(df_hard_returns[df_hard_returns.tail(1).idxmax(axis=1)]).plot(
            ax=ax, color="red")
        l1 = ax.legend(ps, labels, loc=2)
        l2 = ax.legend(
            ["Bitcoin", df_hard_returns.tail(1).idxmax(axis=1)[0]], loc=3)
        ax.add_artist(l1)
        fig.savefig("thesis/plots/strat_random_returns.png")
コード例 #11
0
def setPoints(fname, aviProps, bg):
    frameWidth = aviProps[2]
    frameHeight = aviProps[3]
    fig, ax = showArena(aviProps, bg)

    # 1 point for nest position
    print "Set nest position [1 point]"
    nestPosition = fig.ginput(1)
    nestPosition = nestPosition[0]
    ax.plot(nestPosition[0],nestPosition[1], '+')
    fig.canvas.draw()

    # 4 points for nest area
    print "Set nest area [3 points: lower left, lower right, top]"
    nestArea = fig.ginput(3)
    W = nestArea[1][0] - nestArea[0][0]
    H = nestArea[2][1] - nestArea[1][1]
    rect = plt.Rectangle((nestArea[0][0],nestArea[0][1]),W,H, fc='r', alpha=0.2)
    ax.add_patch(rect)
    fig.canvas.draw()

    # 1 point for middle of arena
    print "Set centre of arena [1 point]"
    arenaCentre = fig.ginput(1)   
    arenaCentre = arenaCentre[0]
    x = [arenaCentre[0], arenaCentre[0]]
    y = [0,frameHeight-60]
    ax.plot(x,y, 'b')
    fig.canvas.draw()

    # 2 points for feeding area
    print "Set feeding area [3 points: lower left, lower right, top]"
    feedingArea = fig.ginput(3)   
    #circle = plt.Circle((feedingArea[0][0],feedingArea[0][1]), radius=feedingArea[1][0]-feedingArea[0][0], fc='c')
    #ax.add_patch(circle)
    W = feedingArea[1][0] - feedingArea[0][0]
    H = feedingArea[2][1] - feedingArea[1][1]
    rect2 = plt.Rectangle((feedingArea[0][0],feedingArea[0][1]),W,H, fc='c', alpha=0.2)
    ax.add_patch(rect2)
    fig.canvas.draw()

    pts = [nestPosition, nestArea, arenaCentre, feedingArea]
    #fsaveName = fname.rstrip(".avi") + "_arena"
    #np.save(fsaveName, ths)
    #print fsaveName, "saved"
    return pts
コード例 #12
0
def plot_box(bb, color='lightgreen'):
    plt.gca().add_patch(
        plt.Rectangle((bb[1], bb[0]),
                      bb[3] - bb[1],
                      bb[2] - bb[0],
                      facecolor='none',
                      edgecolor=color,
                      linewidth=2.0))
コード例 #13
0
def color_box(vid, bbox, ax, color="red"):

    ax.add_patch(
        plt.Rectangle((int(bbox[0]), int(bbox[2])),
                      int(bbox[1] - bbox[0]),
                      int(bbox[3] - bbox[2]),
                      fill=False,
                      edgecolor=color,
                      linewidth=3.5))
コード例 #14
0
def plot_generated_toy_batch(X_real, generator_model, discriminator_model, noise_dim, gen_iter, noise_scale=0.5):

    # Generate images
    X_gen = sample_noise(noise_scale, 10000, noise_dim)
    X_gen = generator_model.predict(X_gen)

    # Get some toy data to plot KDE of real data
    data = load_toy(pts_per_mixture=200)
    x = data[:, 0]
    y = data[:, 1]
    xmin, xmax = -1.5, 1.5
    ymin, ymax = -1.5, 1.5

    # Peform the kernel density estimate
    xx, yy = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
    positions = np.vstack([xx.ravel(), yy.ravel()])
    values = np.vstack([x, y])
    kernel = stats.gaussian_kde(values)
    f = np.reshape(kernel(positions).T, xx.shape)

    # Plot the contour
    fig = plt.figure(figsize=(10,10))
    plt.suptitle("Generator iteration %s" % gen_iter, fontweight="bold", fontsize=22)
    ax = fig.gca()
    ax.contourf(xx, yy, f, cmap='Blues', vmin=np.percentile(f,80), vmax=np.max(f), levels=np.linspace(0.25, 0.85, 30))

    # Also plot the contour of the discriminator
    delta = 0.025
    xmin, xmax = -1.5, 1.5
    ymin, ymax = -1.5, 1.5
    # Create mesh
    XX, YY = np.meshgrid(np.arange(xmin, xmax, delta), np.arange(ymin, ymax, delta))
    arr_pos = np.vstack((np.ravel(XX), np.ravel(YY))).T
    # Get Z = predictions
    ZZ = discriminator_model.predict(arr_pos)
    ZZ = ZZ.reshape(XX.shape)
    # Plot contour
    ax.contour(XX, YY, ZZ, cmap="Blues", levels=np.linspace(0.25, 0.85, 10))
    dy, dx = np.gradient(ZZ)
    # Add streamlines
    # plt.streamplot(XX, YY, dx, dy, linewidth=0.5, cmap="magma", density=1, arrowsize=1)
    # Scatter generated data
    plt.scatter(X_gen[:1000, 0], X_gen[:1000, 1], s=20, color="coral", marker="o")

    l_gen = plt.Line2D((0,1),(0,0), color='coral', marker='o', linestyle='', markersize=20)
    l_D = plt.Line2D((0,1),(0,0), color='steelblue', linewidth=3)
    l_real = plt.Rectangle((0, 0), 1, 1, fc="steelblue")

    # Create legend from custom artist/label lists
    # bbox_to_anchor = (0.4, 1)
    ax.legend([l_real, l_D, l_gen], ['Real data KDE', 'Discriminator contour',
                                     'Generated data'], fontsize=18, loc="upper left")
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax + 0.8)
    plt.savefig("../../figures/toy_dataset_iter%s.jpg" % gen_iter)
    plt.clf()
    plt.close()
コード例 #15
0
def plot_screen(tiles, gazepoints, tolerance=0, filepath=None):
    """ plot an episode screen

    tiles -- a list of tile objects
    gaze points -- a series of sfvec2f objects

    filepath -- optional argument to save the plot to
                a file. The filepath MUST be have a
                valid image extension, e.g. "file.png"
                (bmp, jpg, etc)

    """

    #read gaze points
    gazeX = gazepoints['pixels'].map(lambda x: x.x)
    gazeY = gazepoints['pixels'].map(lambda x: x.y)
    gazeI = gazepoints.index

    #create figure
    fig = plt.figure(figsize=(16, 9))
    ax = fig.add_subplot(111)

    ax.set_xlim(-200, 2120)
    ax.set_ylim(-200, 1280)
    ax.set_ylim(ax.get_ylim()[::-1])
    ax.add_patch(plt.Rectangle((0, 0), 1920, 1080, alpha=0.05, color='b'))
    gax = ax.scatter(gazeX,
                     gazeY,
                     s=10,
                     c=gazeI,
                     cmap=plt.cm.Reds,
                     label='gaze')
    fig.colorbar(gax, format='%d')

    #draw the objects
    tolerances = []
    for tile in tiles:
        if tile.is_selected:
            ax.text(tile.x,
                    tile.y,
                    tile.shape,
                    size='xx-large',
                    weight='bold',
                    color=tile.color,
                    bbox=dict(facecolor='red', alpha=0.5))
        else:
            ax.text(tile.x,
                    tile.y,
                    tile.shape,
                    size='xx-large',
                    weight='bold',
                    color=tile.color)
        #draw the tolerance circles
        circle = plt.Circle((tile.x, tile.y), tolerance, color='r', fill=False)
        ax.add_patch(circle)
    if filepath is not None:
        fig.savefig(filepath, format=filepath.split('.')[1])
コード例 #16
0
ファイル: jo_plot.py プロジェクト: jbecherer/johannes_py_tbx
def mark_period(ax, xl, ec='k', Linewidth=1, fill=False, fc=(1, 1, 1, .5)):
    """ plots a rectagular box in plot with height according to axis given """
    yl = ax.get_ylim()
    p = plt.Rectangle((xl[0], yl[0]),
                      np.diff(xl),
                      np.diff(yl),
                      edgecolor=ec,
                      fill=fill,
                      Linewidth=Linewidth,
                      facecolor=fc)
    ax.add_patch(p)
コード例 #17
0
def plotArena(aviProps, pmts, bg):
    frameWidth = aviProps[2]
    frameHeight = aviProps[3]
    fig, ax = showArena(aviProps, bg)
    fig.show() 

    nestPosition, nestArea, arenaCentre, feedingArea = pmts[2], pmts[3], pmts[4], pmts[5]
    ax.plot(nestPosition[0],nestPosition[1], '+')
    W = nestArea[1][0] - nestArea[0][0]
    H = nestArea[2][1] - nestArea[1][1]
    rect = plt.Rectangle((nestArea[0][0],nestArea[0][1]),W,H, fc='r', alpha=0.2)
    ax.add_patch(rect)
    x = [arenaCentre[0], arenaCentre[0]]
    y = [0,frameHeight-60]
    ax.plot(x,y, 'b')
    W = feedingArea[1][0] - feedingArea[0][0]
    H = feedingArea[2][1] - feedingArea[1][1]
    rect2 = plt.Rectangle((feedingArea[0][0],feedingArea[0][1]),W,H, fc='c', alpha=0.2)
    ax.add_patch(rect2)
    fig.canvas.draw()
コード例 #18
0
def slide_7_2():
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    rect = plt.Rectangle((0.2, 0.75), 0.4, 0.15, color='k', alpha=0.3)
    circ = plt.Circle((0.7, 0.2), 0.15, color='b', alpha=0.3)
    pgon = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]],
                       color='g',
                       alpha=0.5)
    ax.add_patch(rect)
    ax.add_patch(circ)
    ax.add_patch(pgon)
コード例 #19
0
def plot_image(fileobj, filename=None, show_corrects=False, bare=False):
    img = gv.img.load_image(fileobj.path)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    s = dict(cmap=plt.cm.gray) if img.ndim == 2 else {}
    ax.imshow(img, **s)
    if bare:
        ax.set_xticks([])
        ax.set_yticks([])

    for bbobj in fileobj.boxes:
        bb = bbobj.box
        if show_corrects:
            if bbobj.correct:
                color = 'lightgreen'
            else:
                color = 'red'
        else:
            if bbobj.difficult:
                color = 'red'
            else:
                color = 'lightgreen'
        plt.gca().add_patch(
            plt.Rectangle((bb[1], bb[0]),
                          bb[3] - bb[1],
                          bb[2] - bb[0],
                          facecolor='none',
                          edgecolor=color,
                          linewidth=2.0))
        if not bare:
            plt.text(bb[1],
                     bb[0],
                     "{0:.2f}".format(bbobj.confidence),
                     color='white',
                     size=6,
                     ha='left',
                     va='bottom')
        #plt.gca().add_patch(plt.Rectangle((bb[0], bb[1]), bb[2]-bb[0], bb[3]-bb[1], facecolor='none', edgecolor='lightgreen', linewidth=2.0))
    if not bare:
        ax.set_title("img_id = {0}".format(fileobj.img_id))
    else:
        plt.tight_layout()

    if filename is not None:
        plt.savefig(filename)
    else:
        plt.show()
コード例 #20
0
def hinton(matrix, max_weight=None, ax=None):
    """Draw Hinton diagram for visualizing a weight matrix."""
    ax = ax if ax is not None else plt.gca()

    if not max_weight:
        max_weight = 2 ** np.ceil(np.log(np.abs(matrix).max()) / np.log(2))

    ax.patch.set_facecolor('gray')
    ax.set_aspect('equal', 'box')
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    for (x, y), w in np.ndenumerate(matrix):
        color = 'white' if w > 0 else 'black'
        size = np.sqrt(np.abs(w) / max_weight)
        rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,
                             facecolor=color, edgecolor=color)
        ax.add_patch(rect)

    ax.autoscale_view()
    ax.invert_yaxis()
コード例 #21
0
def show_item(item):
    img, bbox, label, scale = item
    img = img.transpose(1, 2, 0)
    img = denormalize(img)

    title = 'Label: ' + str(label) + " shape: " + str(img.shape)

    plt.figure()
    plt.title(title)
    plt.imshow(img)
    ax = plt.gca()
    for i in range(bbox.shape[0]):
        xy = (bbox[i, 1], bbox[i, 0])
        w, h = bbox[i, 3] - bbox[i, 1], bbox[i, 2] - bbox[i, 0]
        rect = plt.Rectangle(xy,
                             w,
                             h,
                             fill=False,
                             edgecolor='red',
                             linewidth=1)
        ax.add_patch(rect)
    plt.axis('off')
    plt.show()
コード例 #22
0
ファイル: plot.py プロジェクト: ajmendez/PySurvey
def box(x=None, y=None, normal=False, fill=True, ax=None, **kwargs):
    oline = kwargs.pop('outline', False)
    outline_prop = kwargs.pop('outline_prop', {})
    tmp = dict(
        color='0.2',
        alpha=0.4,
        linewidth=2,
    )

    if ax is None:
        ax = pylab.gca()
    axt = ax.axis()
    if normal:
        tmp['transform'] = ax.transAxes
    else:
        tmp['transform'] = ax.transData

    # if x is not None and percent: x = np.diff(axt[:2])*np.array(x) + axt[0]
    # if y is not None and percent: y = np.diff(axt[2:])*np.array(y) + axt[2]
    if x is None: x = axt[:2]
    if y is None: y = axt[2:]

    dx = np.diff(x)[0]
    dy = np.diff(y)[0]
    # use date2num
    # if isinstance(x[0], datetime): dx = dx.days
    # if isinstance(y[0], datetime): dy = dy.total_seconds()

    if oline or (not fill):
        tmp['facecolor'] = 'none'
        tmp['edgecolor'] = kwargs.pop('color', tmp.pop('color'))
    tmp.update(kwargs)
    patch = pylab.Rectangle((x[0], y[0]), dx, dy, **tmp)
    if oline:
        outline(patch, **outline_prop)
    ax.add_patch(patch)
コード例 #23
0
ファイル: knn.py プロジェクト: ryankuhle/unit4lesson4
del iris_data['petal_width']

# Create scatterplot of sepal_length by sepal_width colored by class
color_dict = {
    'Iris-setosa': 'red',
    'Iris-versicolor': 'blue',
    'Iris-virginica': 'green'
}
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.title('Iris Classification by Sepal')
plt.scatter(iris_data['sepal_length'],
            iris_data['sepal_width'],
            color=[color_dict[i] for i in iris_data['iris_class']])
plt.grid()
p1 = plt.Rectangle((0, 0), 0.1, 0.1, fc=color_dict['Iris-setosa'])
p2 = plt.Rectangle((0, 0), 0.1, 0.1, fc=color_dict['Iris-versicolor'])
p3 = plt.Rectangle((0, 0), 0.1, 0.1, fc=color_dict['Iris-virginica'])
plt.legend((p1, p2, p3), ('Iris-setosa', 'Iris-versicolor', 'Iris-virginica'),
           loc='best')
#plt.show()

# Random point for plotting
random_x = random.uniform(4.0, 8.5)
random_y = random.uniform(1.5, 5.0)

# measures the distance from random point against all points in data frame
# records info in data frame column "distance"
for i in iris_data.index:
    train_x = iris_data['sepal_length'][i]
    train_y = iris_data['sepal_width'][i]
コード例 #24
0
         title,
         horizontalalignment='center',
         fontsize=35,
         transform=ax.transAxes)

ax.tick_params(axis='x', labelsize=15)
plt.xticks(rotation=70)

xticks = ax.xaxis.get_major_ticks()
xticks[0].label1.set_visible(False)

ax.tick_params(axis='y', labelsize=15)

#ax.xaxis.set_label_coords(1.00, -0.03)
#ax.margins(0.1, 0)

plt.xlim(0, 1)

#y_max = Y1.max() * 1.2
plt.ylim((-0.01, 0.1))

p = []
for i in color:
    p.extend([plt.Rectangle((0, 0), 1, 1, fc=i, alpha=1)])

lgd = ax.legend(p, words, loc='center', bbox_to_anchor=(1.15, 0.5))

path = '/Users/gerauddaspremont/Dropbox/project/thesis_1/Figures'
filename = 'lambdavsFreq2' + w.replace(' ', '') + '.pdf'
filename = os.path.join(path, filename)
fig.savefig(filename, bbox_inches='tight')
コード例 #25
0
def plot_bars(  # noqa
    x, heights, width=None, align="center", y_base=0, ax=None, **rectangle_kws
):  # pylint: disable=too-many-arguments,too-many-locals,too-many-branches,too-many-statements,line-too-long # noqa
    """Plot rectangular bars.

    Args:
        x (List): X points of the bars. Can handle dates.
        heights (List): Heights of the bars, can be negative.
        width (float or Any): Used with the center to determine the bar
            dimensions.
        align (str): Where to align the x.
            'center': x is the center.
            'left': x is the left edge.
            'right': x is the right edge.
        y_base (float): Base of the bars.
        ax (matplotlib.axes.Axes): Axis object, otherwise uses plt.gca().
        **rectangle_kws: passed to all plt.Rectangle(**rectangle_kws).

    Returns:
        List[plt.Rectangle]: List of the rectangle patches.

    """
    ax = ax or plt.gca()

    if len(x) == 0:
        # don't plot anything because there isn't any
        return []

    # is x axis datetime objects?
    xpt0 = x[0]
    x_is_datetime = isinstance(xpt0, datetime)

    # get width of the bars
    if width is None:
        if len(x) > 1:
            xpt1 = x[1]
            diff = xpt1 - xpt0
            width = diff * 0.8
        else:
            if x_is_datetime:
                width = timedelta(days=1)
            else:
                width = 1
    elif isinstance(width, (float, int)) and x_is_datetime:
        width = timedelta(days=width)

    half_width = width / 2.0

    # get the x and y bounds
    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()

    is_first = True
    rectangles = []
    for xpt, height in zip(x, heights):
        if height < 0:
            height = abs(height)
            rect_ymin = y_base - height
            rect_ymax = y_base
        else:
            rect_ymin = y_base
            rect_ymax = rect_ymin + height

        if align == "center":
            rect_xmin = xpt - half_width
            rect_xmax = xpt + half_width
        elif align == "left":
            rect_xmin = xpt
            rect_xmax = xpt + width
        elif align == "right":
            rect_xmin = xpt - width
            rect_xmax = xpt
        else:
            raise ValueError(
                f'unknown value for where "{align}" not one of (center, right, left)'
            )

        kws = {
            "alpha": 0.8,
        }
        kws.update(rectangle_kws)
        if not is_first:
            kws.pop("label", None)
        rect = plt.Rectangle(
            xy=(rect_xmin, rect_ymin),
            height=height,
            width=width,
            **kws,
        )
        ax.add_patch(rect)
        rectangles.append(rect)

        if isinstance(rect_xmin, datetime) and isinstance(xmin, float):
            if xmin == 0.0:
                xmin = rect_xmin
            else:
                xmin = plt.matplotlib.dates.num2date(xmin).replace(
                    tzinfo=rect_xmin.tzinfo
                )
        if isinstance(rect_xmax, datetime) and isinstance(xmax, float):
            if xmax == 1.0:
                xmax = rect_xmax
            else:
                xmax = plt.matplotlib.dates.num2date(xmax).replace(
                    tzinfo=rect_xmax.tzinfo
                )

        xmin = min(xmin, rect_xmin)
        xmax = max(xmax, rect_xmax)
        ymin = min(ymin, rect_ymin)
        ymax = max(ymax, rect_ymax)

        is_first = False

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    return rectangles
コード例 #26
0
ファイル: statistics.py プロジェクト: hagne/atm-py
    def plot_percentiles(self,
                         ax=None,
                         box_width=0.2,
                         wisker_size=20,
                         mean_size=10,
                         median_size=10,
                         line_width=1.5,
                         xoffset=0,
                         color=0,
                         tickbase=1):
        """
        This will plot the percentiles of the data ([5, 25, 50, 75, 95]. In addition, the mean (o) and median (_) are shown.

        Parameters
        ----------
        ax
        box_width
        wisker_size
        mean_size
        median_size
        line_width
        xoffset
        color
        tickbase

        Returns
        -------
        f, a, boxes, vlines, wisker_tips, mean
        """
        if type(color) == int:
            color = _plt.rcParams['axes.prop_cycle'].by_key()['color'][color]
            col = _plt_tools.colors.Color(color, model='hex')
        elif type(color) == str:
            col = _plt_tools.colors.Color(color, model='hex')
        else:
            col = _plt_tools.colors.Color(color, model='rgb')

        col.saturation = 0.3
        color_bright = col.rgb

        if ax:
            a = ax
            f = a.get_figure()
        else:
            f, a = _plt.subplots()

        boxes = []
        vlines = []
        xordinal = []
        for row in self.percentiles.iterrows():
            #             width = 10
            x = row[0] + xoffset
            xordinal.append(x)

            # box
            # y = (row[1][75] + row[1][25]) / 2
            y = row[1][25]
            height = row[1][75] - row[1][25]
            box = _plt.Rectangle(
                (x - box_width / 2, y),
                box_width,
                height,
                #                         ha = 'center'
            )
            box.set_facecolor([1, 1, 1, 1])
            a.add_patch(box)
            boxes.append(box)
            # wiskers
            y = (row[1][95] + row[1][5]) / 2
            vl = a.vlines(x, row[1][5], row[1][95])
            vlines.append(vl)

        for b in boxes:
            b.set_linewidth(line_width)
            b.set_facecolor(color_bright)
            b.set_edgecolor(color)
            b.set_zorder(2)

        for vl in vlines:
            vl.set_color(color)
            vl.set_linewidth(line_width)
            vl.set_zorder(1)

        # wm_lw = 2
        wisker_tips = []
        if wisker_size:
            g, = a.plot(xordinal, self.percentiles[5], ls='')
            wisker_tips.append(g)

            g, = a.plot(xordinal, self.percentiles[95], ls='')
            wisker_tips.append(g)

        for wt in wisker_tips:
            wt.set_markeredgewidth(line_width)
            wt.set_color(color)
            wt.set_markersize(wisker_size)
            wt.set_marker('_')

        mean = None
        if mean_size:
            g, = a.plot(xordinal, self.percentiles['mean'], ls='')
            g.set_marker('o')
            g.set_markersize(mean_size)
            g.set_zorder(20)
            g.set_markerfacecolor('None')
            g.set_markeredgewidth(line_width)
            g.set_markeredgecolor(color)
            mean = g

        median = None
        if median_size:
            g, = a.plot(xordinal, self.percentiles['median'], ls='')
            g.set_marker('_')
            g.set_markersize(median_size)
            g.set_zorder(20)
            g.set_markeredgewidth(line_width)
            g.set_markeredgecolor(color)
            median = g

        # a.xaxis.set_major_locator(_MonthLocator())
        # a.xaxis.set_major_formatter(_DateFormatter('%b'))
        try:
            a.set_ylim(_np.nanmin(self.percentiles.drop(['n_valid'], axis=1)),
                       _np.nanmax(self.percentiles.drop(['n_valid'], axis=1)))
        except:
            pass

        try:
            a.set_xlim(self.percentiles.index.min(),
                       self.percentiles.index.max())
        except:
            pass

        mjl = _MultipleLocator(tickbase)
        a.xaxis.set_major_locator(mjl)

        # a.relim()
        # a.autoscale_view(tight=True)
        # f.autofmt_xdate()
        return f, a, boxes, vlines, wisker_tips, mean, median
コード例 #27
0
ファイル: fit_border.py プロジェクト: GoJian/TEMareels
def get_border_points(img, rel_threshold=0.1, dev_bg=2, xmin=0, xmax=np.inf, ymin=0, ymax=np.inf, \
                      medfilt_radius=11, window_size=None, interp_out=False, verbosity=1, **kwargs):
    """
    Estimate x coordinates of the aperture border in wq-maps
    for each y-line of the (previously binned) image.

    img           ... 2D array image (Ny,Nx), binned along y
    rel_threshold ... (opt) relative threshold
    dev           ... (opt) deviation from linear fit w.r.t. std.dev.
    dev_bg        ... (opt) background noise level w.r.t. sdt.dev of noise
    medfilt_radius... (opt) filtering of input signal
    xmin,xmax     ... (opt) restricts image for fitting (px)
    ymin,ymax
    window_size   ... (opt) restrict to window around max intensity (px) 
    interp_out    ... (opt) bool indicating, if outliers (NaN's) shall be 
                            replaced with interpolated values ( 
    verbosity     ... (opt) verbosity (0=silent, 2=plotting fit, 3=debug)

    RETURNS left and right border as list of points (x,y) with length ymax-ymin 
  """

    # image axis order (y,x)
    xmax = min(xmax, img.shape[1])
    ymax = min(ymax, img.shape[0])
    xmin = max(xmin, 0)
    ymin = max(ymin, 0)
    Nx = xmax - xmin
    Ny = ymax - ymin
    assert Nx > 0 and Ny > 0
    xleft = np.empty(Ny)
    xright = np.empty(Ny)
    x = np.arange(xmin, xmax)

    # 1. try to find left and right border for each line y
    #    in the cropped image, i.e., ymin <= y < ymax, xmin <= x < xmax
    for iy, y in enumerate(np.arange(ymin, ymax)):

        # smoothing and background subtraction
        line = medfilt1D(img[y, xmin:xmax], medfilt_radius)
        out = outliers(x, line, iterations=3, dev=2)
        bg = line[~out]
        # linear background signal
        line -= np.mean(bg)

        # window around max intensity
        ixcenter = np.argmax(line)
        if window_size is not None:
            ixmin = max(ixcenter - window_size / 2, 0)
            ixmax = min(ixcenter + window_size / 2, Nx - 1)
        else:
            ixmin = 0
            ixmax = Nx - 1

        # find first point from left/right above threshold
        thresh = line[ixcenter] * rel_threshold
        if thresh < dev_bg * np.std(
                bg):  # S/N too low (threshold below std.dev)
            xleft[iy] = xright[iy] = np.nan
        else:
            # image coordinates !
            xleft[iy] = x[ixmin + threshold(line[ixmin:ixcenter], thresh)]
            xright[iy] = x[ixmax - threshold(line[ixmax:ixcenter:-1], thresh)]

        # DEBUG
        if verbosity > 10 and iy == (ymax + ymin) / 2:
            plt.figure()
            plt.title("line at y = %d" % (Ny / 2))
            plt.plot(img[y], 'k-', label="intensity")
            plt.plot(x[~out], bg, 'b-', label="background")
            plt.axhline(thresh + np.mean(bg), color='g')
            plt.axvline(xleft[iy], color='r')
            plt.axvline(xright[iy], color='r', label="border")
            plt.legend(loc=2)

    # 2. determine outliers
    y = np.arange(ymin, ymax)
    iout_left = outliers(y, xleft, **kwargs)
    iout_right = outliers(y, xright, **kwargs)

    # 3. plotting
    if verbosity > 2:
        plt.figure()
        plt.title("Debug: Edge fitting")
        plt.xlabel("x [px]")
        plt.ylabel("y [px]")
        plt.imshow(np.log(1 + np.abs(img)), cmap=plt.cm.gray, aspect='auto')
        #plt.imshow(img,vmin=0,vmax=np.mean(img)*10,cmap=plt.cm.gray, aspect='auto');
        plt.plot(xleft, y, 'g+', mew=2, label='border')
        plt.plot(xright, y, 'g+', mew=2)
        plt.plot(xleft[iout_left], y[iout_left], 'r+', mew=2, label='outliers')
        plt.plot(xright[iout_right], y[iout_right], 'r+', mew=2)
        plt.gca().add_patch(
            plt.Rectangle((xmin, ymin),
                          Nx,
                          Ny,
                          lw=3,
                          ec='red',
                          fc='0.5',
                          alpha=0.2))
        plt.xlim(0, img.shape[1])
        plt.ylim(img.shape[0] - 1, 0)
        plt.legend(loc=2)

    # 4. calculate fitted points at outliers
    xleft[iout_left] = np.nan
    xright[iout_right] = np.nan
    if interp_out:
        xleft = replace_nan(y, xleft)
        xright = replace_nan(y, xright)

    # 5. return border as list of (x,y)-points
    return np.vstack((xleft, y)), np.vstack((xright, y))
コード例 #28
0
def draw_region(start, end,  height, **kwargs):
    """ Draw a rectangular patch that spans coordinates start to end, with given height.
    """
    r = pylab.Rectangle((start, 0), abs(start-end), height, **kwargs)
    pylab.gca().add_patch(r)
    pylab.draw()
コード例 #29
0
def cross_correl_plot(data, FIGSIZE=(7,7), wspace=.5, hspace=.5, right=0.98, left=0.1,\
                      many_data=False):
    """
    'data' should be an array of dictionaries with keys 'vec' and labels 'label'
    """

    fig, AX = plt.subplots(len(data) - 1, len(data) - 1, figsize=FIGSIZE)
    plt.subplots_adjust(wspace=wspace, hspace=hspace, right=right, left=left)

    mymap = get_linear_colormap(color1='white', color2='gray')

    significance = np.array([1e-3, 2e-2, 1e-1, 1])

    for i in range(len(data) - 1):
        for j in range(i + 1, len(data)):
            AX[j - 1, i].plot(data[i]['vec'], data[j]['vec'], 'ko')
            if not many_data:
                set_plot(AX[j - 1, i],
                         xlabel=data[i]['label'],
                         ylabel=data[j]['label'])
            else:
                if ((i == 0) and (j == len(data) - 1)):
                    set_plot(AX[j - 1, i],
                             xlabel=data[i]['label'],
                             ylabel=data[j]['label'])
                elif (j == len(data) - 1):
                    set_plot(AX[j - 1, i],
                             xlabel=data[i]['label'],
                             yticks_labels=[])
                elif (i == 0):
                    set_plot(AX[j - 1, i],
                             ylabel=data[j]['label'],
                             xticks_labels=[])
                else:
                    set_plot(AX[j - 1, i], xticks_labels=[], yticks_labels=[])

            cc, pp = pearsonr(data[i]['vec'], data[j]['vec'])

            x = np.linspace(data[i]['vec'].min(), data[i]['vec'].max())
            AX[j-1, i].plot(x,\
                np.polyval(np.polyfit(np.array(data[i]['vec'], dtype='f8'),\
                                      np.array(data[j]['vec'], dtype='f8'), 1), x),\
                                      'k--', lw=.5)

            ii = np.arange(len(significance))[significance - pp >= 0][0]
            color = -1. * (ii - len(significance) + 1) / (len(significance) -
                                                          1)
            xmin, xmax = AX[j - 1, i].get_xaxis().get_view_interval()
            ymin, ymax = AX[j - 1, i].get_yaxis().get_view_interval()
            AX[j-1, i].add_patch(plt.Rectangle((xmin, ymin),\
                                               xmax-xmin, ymax-ymin, color=mymap(1.*color,1)))

    ax = plt.axes([.7, .7, .02, .2])
    build_bar_legend(np.arange(len(significance)+1),\
                     ax, mymap,\
                     ticks_labels=['n.s.', '$<$0.1', '$<$0.02', '$<$0.001'],
                     label='Significance \n \n (p, Pearson correl.)')

    for ax in AX.flatten():
        if ax.get_xaxis().get_view_interval()[1] == 1.:
            ax.axis('off')

    return fig
コード例 #30
0
def plot_policy(env, args, x_range, y_range, policy, prefix):
    """
    Plots 2d graph depicting a policy. Right now I don't have any mechanism to break ties, I expect the user to have
    done that already. TODO: I don't support two actions at the same time, so I'll always depict only one action. I
    should support this in the future.

    :param env: object containing the environment's features, I access it to plot what I want
    :param args: list of all arguments passed at the execution so we can access the paths we are interested at
    :param x_range: one of the dimensions of the grid world
    :param y_range: the other dimension of the grid world
    :param policy: actual policy to be plotted. It should be encoded as an integer per state.
    :param prefix: string that will be used as the filename of the generated graph
    """
    plt.clf()
    plt.close()

    from pylab import rcParams
    rcParams['figure.figsize'] = y_range, x_range

    plt.xlim([0, y_range])
    plt.ylim([0, x_range])

    for i in range(y_range):
        plt.axvline(i, color='k', linestyle=':')
    plt.axvline(y_range, color='k', linestyle=':')

    for j in range(x_range):
        plt.axhline(j, color='k', linestyle=':')
    plt.axhline(x_range, color='k', linestyle=':')

    for idx in range(len(policy)):
        i, j = env.get_state_xy(idx)

        dx = 0
        dy = 0
        if policy[idx] == 0:  # up
            dy = 0.001
        elif policy[idx] == 1:  # right
            dx = 0.001
        elif policy[idx] == 2:  # down
            dy = -0.001
        elif policy[idx] == 3:  # left
            dx = -0.001

        if (env._matrix_mdp[i][j] != -1
                and policy[idx] == 4) or (env._goal_x == i
                                          and env._goal_y == j):  # termination
            termination = plt.Rectangle((j, x_range - i - 1), 1, 1, color='r')
            plt.gca().add_artist(termination)

        elif env._matrix_mdp[i][j] != -1:
            plt.arrow(j + 0.5 - 250 * dx,
                      x_range - i + 0.5 - 1 - 250 * dy,
                      dx,
                      dy,
                      head_width=0.2,
                      head_length=0.5,
                      fc='k',
                      ec='k')
        else:
            plt.gca().add_patch(
                patches.Rectangle(
                    (j, x_range - i - 1),  # (x,y)
                    1.0,  # width
                    1.0,  # height
                    facecolor="gray"))

    plt.savefig(args.output + prefix + '.png')
    plt.clf()