Beispiel #1
0
def make_matplot_kde_shot_chart(df, player_name, player_id, year, season_type, chart_type):
    player_pic = get_player_picture(player_id, player_name)

    # create our jointplot

    # get our colormap for the main kde plot
    # Note we can extract a color from cmap to use for
    # the plots that lie on the side and top axes
    cmap = plt.cm.viridis

    # n_levels sets the number of contour lines for the main kde plot
    joint_shot_chart = sns.jointplot(df.LOC_X, df.LOC_Y, stat_func=None,
                                     kind='kde', space=0, color=cmap(0.1),
                                     cmap=cmap, n_levels=50, extent=[-250, 250, 422.5, -47.5])

    joint_shot_chart.fig.set_size_inches(12, 11)

    # A joint plot has 3 Axes, the first one called ax_joint
    # is the one we want to draw our court onto and adjust some other settings
    ax = joint_shot_chart.ax_joint
    draw_court(ax)

    # Adjust the axis limits and orientation of the plot in order
    # to plot half court, with the hoop by the top of the plot
    ax.set_xlim(-250, 250)
    ax.set_ylim(422.5, -47.5)

    # Get rid of axis labels and tick marks
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.tick_params(labelbottom='off', labelleft='off')

    # Add a title
    title = player_name + ' ' + dg.get_year_string(year) + ' ' + season_type
    ax.set_title(title,
                 y=1.2, fontsize=18)

    # Add Data Scource and Author
    ax.text(-250, 445, 'Data Source: stats.nba.com',
            fontsize=12)

    # Add Harden's image to the top right
    # First create our OffSetImage by passing in our image
    # and set the zoom level to make the image small enough
    # to fit on our plot
    img = OffsetImage(player_pic, zoom=0.6)
    # Pass in a tuple of x,y coordinates to set_offset
    # to place the plot where you want, I just played around
    # with the values until I found a spot where I wanted
    # the image to be
    img.set_offset((987, 907))
    # add the image
    ax.add_artist(img)

    file_path = '../charts/' + chart_type + '/kde/' + player_name + '_' + str(
        year) + '_' + season_type + '.png'
    dg.create_directories_and_check_for_file(file_path)
    plt.savefig(file_path)
    plt.close()
    def background_image(self, file):
        """Set the file image as background image"""
        if self.bg_img:
            self.bg_img.remove()

        datafile = get_sample_data(file)
        img = plt.imread(datafile)
        im = OffsetImage(img)
        im.set_zoom(min(1. * self.canvas.window.get_size()[0] / len(im.properties()['data'][0]),
                        1. * self.canvas.window.get_size()[1] / len(im.properties()['data'])))
        self.bg_img = AnnotationBbox(im, (0.5, 0.5), xycoords='data', frameon=False)
        self.bg_img.set_zorder(-1)
        plt.gca().add_artist(self.bg_img)
        self.do_refresh()
Beispiel #3
0
def make_matplot_hexbin_shot_chart(df, player_name, player_id, year, season_type, chart_type):
    player_pic = get_player_picture(player_id, player_name)

    # create our jointplot

    cmap = plt.cm.coolwarm
    plt.axis([-250, 250, 422.5, -47.5])
    joint_shot_chart = sns.jointplot(df.LOC_X, df.LOC_Y, stat_func=None, reduce_C_function=np.sum,
                                     kind='hex', space=0, color=cmap(.2), cmap=cmap, extent=[-250, 250, 422.5, -47.5],
                                     gridsize=30)

    joint_shot_chart.fig.set_size_inches(12, 11)

    # A joint plot has 3 Axes, the first one called ax_joint
    # is the one we want to draw our court onto
    ax = joint_shot_chart.ax_joint
    draw_court(ax)

    # Adjust the axis limits and orientation of the plot in order
    # to plot half court, with the hoop by the top of the plot
    ax.set_xlim(-250, 250)
    ax.set_ylim(422.5, -47.5)

    # Get rid of axis labels and tick marks
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.tick_params(labelbottom='off', labelleft='off')

    # Add a title
    ax.set_title(player_name + ' ' + dg.get_year_string(year) + ' ' + season_type,
                 y=1.2, fontsize=18)

    img = OffsetImage(player_pic, zoom=0.6)
    img.set_offset((987, 907))
    ax.add_artist(img)

    file_path = '../charts/' + chart_type + '/hexbin/' + player_name + '_' + str(
        year) + '_' + season_type + '.png'
    dg.create_directories_and_check_for_file(file_path)
    plt.savefig(file_path)
    plt.close()
Beispiel #4
0
def make_matplot_scatter_shot_chart(df, player_name, player_id, year, season_type, chart_type):
    player_pic = get_player_picture(player_id, player_name)

    # create our jointplot
    joint_shot_chart = sns.jointplot(df.LOC_X, df.LOC_Y, stat_func=None, kind='scatter', space=0, alpha=0.5)

    joint_shot_chart.fig.set_size_inches(12, 11)

    # A joint plot has 3 Axes, the first one called ax_joint
    # is the one we want to draw our court onto and adjust some other settings
    ax = joint_shot_chart.ax_joint
    draw_court(ax)

    # Adjust the axis limits and orientation of the plot in order
    # to plot half court, with the hoop by the top of the plot
    ax.set_xlim(-250, 250)
    ax.set_ylim(422.5, -47.5)

    # Get rid of axis labels and tick marks
    ax.set_xlabel('')
    ax.set_ylabel('')
    ax.tick_params(labelbottom='off', labelleft='off')

    # Add a title
    ax.set_title(player_name + ' ' + dg.get_year_string(year) + ' ' + season_type,
                 y=1.2, fontsize=18)

    img = OffsetImage(player_pic, zoom=.7)
    img.set_offset((987, 907))
    ax.add_artist(img)

    file_path = '../charts/' + chart_type + '/scatter/' + player_name + '_' + str(
        year) + '_' + season_type + '.png'
    dg.create_directories_and_check_for_file(file_path)
    plt.savefig(file_path)
    plt.close()
Beispiel #5
0
plt.figure(figsize=(11,9))

# plot the figure using matplotlib's hexbin plot methods
im = plt.hexbin(shot_df.LOC_X,shot_df.LOC_Y, C=shot_df.ZONE_COLOR, marginals=False,
		   bins='log', cmap=cmap, gridsize=85, edgecolors='#152435')

# draw the court lines on the current plot
draw_court()

# set the limits of the court to display the half court
plt.ylim([424.5,-49.5])
plt.xlim([-252,252])

# take off axis tick marks, no use for them in this context
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())

#get the player's picture from nba.com
pic = urlretrieve("http://stats.nba.com/media/players/230x185/"+str(playerID)+".png", str(playerID)+".png")
player_pic = plt.imread(pic[0])
img = OffsetImage(player_pic, zoom=0.6)
img.set_offset((600,75))
plt.gca().add_artist(img)

# add a title
plt.title(playerName+' FGA \n'+year+' Reg. Season', fontsize=20, y=1.01)

# set the background color
plt.gca().set_axis_bgcolor('#152435')
plt.show()
Beispiel #6
0
def make_scatter_plot(X,
                      F,
                      train_index,
                      test_index,
                      filter=None,
                      predicted_labels=[],
                      show_diag=False,
                      axis='normal'):
    '''This scatter plot function allows us to show the images.
		predicted_labels can either be: 
				- None (queries shown as question marks)
				- a vector of +-1 predicted values
				- the string "GroundTruth" (to display the test images).
		Other optional arguments: 
			show_diag: add diagonal dashed line if True.
			axis: make axes identical if 'square'.'''
    fruit = np.array(['B', 'A'])
    fig, ax = plt.subplots()
    # Plot training examples
    x = X[train_index, 0]
    y = X[train_index, 1]
    f = F[train_index]
    ax.scatter(x, y, s=750, marker='o')

    for x0, y0, path in zip(x, y, f):
        img = get_image(path)
        if filter:
            img = filter(img)
        ab = AnnotationBbox(OffsetImage(img), (x0, y0), frameon=False)
        ax.add_artist(ab)

    # Plot test examples
    x = X[test_index, 0]
    y = X[test_index, 1]

    if len(predicted_labels) > 0 and not (predicted_labels == "GroundTruth"):
        label = (predicted_labels + 1) / 2
        ax.scatter(x, y, s=250, marker='s', color='k')
        for x0, y0, lbl in zip(x, y, label):
            ax.text(x0 - 0.05,
                    y0 - 0.05,
                    fruit[int(lbl)],
                    color="w",
                    fontsize=12,
                    weight='bold')
    elif predicted_labels == "GroundTruth":
        f = F[test_index]
        ax.scatter(x, y, s=500, marker='s', color='k')
        for x0, y0, path in zip(x, y, f):
            img = get_image(path)
            img = filter(img)
            ab = AnnotationBbox(OffsetImage(img), (x0, y0), frameon=False)
            ax.add_artist(ab)
    else:  # Plot UNLABELED test examples
        f = F[test_index]
        ax.scatter(x, y, s=250, marker='s', c='k')
        ax.scatter(x, y, s=100, marker='$?$', c='w')

    if axis == 'square':
        ax.set_aspect('equal', adjustable='box')
    plt.xlim(-3, 3)
    plt.ylim(-3, 3)
    plt.xlabel('$x_1$ = Redness')
    plt.ylabel('$x_2$ = Elongation')

    # Add line on the diagonal
    if show_diag:
        plt.plot([-3, 3], [-3, 3], 'k--')
    return
Beispiel #7
0
def create_story(df: pd.DataFrame):

    #df = df[df['Ascent Type'] == 'Onsight'][df['Style'] == 'Trad'].sort_values('Ascent Date')
    df = df.sort_values('Ascent Date')

    fig = plt.figure(figsize=(14, 9))
    ax = fig.add_subplot(1, 1, 1)
    major_ticks = np.arange(0, 26)
    ax.set_yticks(major_ticks)
    ax.set_xticks(major_ticks)
    ax.set_xlim(left=0, right=20)
    ax.set_ylim(bottom=0, top=20)
    ax.set_ylabel('Grade')
    ax.set_xlabel('Count')

    #counts = get_ascent_counts(df.iloc[:3])
    counts = get_ascent_counts(df.iloc[:0])
    sum_ = copy.copy(counts['trad_onsights'])
    trad_onsights_barh = plt.barh(range(1, 25),
                                  counts['trad_onsights'],
                                  color='green',
                                  label='Trad onsight')
    sport_onsights_barh = plt.barh(range(1, 25),
                                   counts['sport_onsights'],
                                   left=sum_,
                                   color='#98ff98',
                                   label='Sport onsight')
    sum_ += counts['sport_onsights']
    trad_flashes_barh = plt.barh(range(1, 25),
                                 counts['trad_flashes'],
                                 left=sum_,
                                 color='#800020',
                                 label='Trad flash')
    sum_ += counts['trad_flashes']
    #plt.barh(range(1, 25), sport_flashes, left = trad_onsights + sport_onsights + trad_flashes, color='orange')
    trad_redpoints_barh = plt.barh(range(1, 25),
                                   counts['trad_redpoints'],
                                   left=sum_,
                                   color='red',
                                   label='Trad redpoint')
    sum_ += counts['trad_redpoints']
    #plt.barh(range(1, 25), sport_redpoints, left = trad_onsights + sport_onsights + trad_flashes + sport_flashes + trad_redpoints, color='#FF00FF')
    pinkpoints_barh = plt.barh(range(1, 25),
                               counts['pinkpoints'],
                               left=sum_,
                               color='pink',
                               label='Pinkpoint (sport or trad)')
    sum_ += counts['pinkpoints']
    cleans_barh = plt.barh(range(1, 25),
                           counts['cleans'],
                           left=sum_,
                           color='xkcd:sky blue',
                           label='Clean lead (yoyo, simulclimbing)')
    sum_ += counts['cleans']
    clean_seconds_barh = plt.barh(range(1, 25),
                                  counts['clean_seconds'],
                                  left=sum_,
                                  color='#FFA500',
                                  label='Clean second')
    sum_ += counts['clean_seconds']
    clean_topropes_barh = plt.barh(range(1, 25),
                                   counts['clean_topropes'],
                                   left=sum_,
                                   color='#FFFF00',
                                   label='Clean toprope')
    sum_ += counts['clean_topropes']
    battle_to_top_barh = plt.barh(
        range(1, 25),
        counts['battle_to_top'],
        left=sum_,
        color='gray',
        label='Battle to top (hangdog, second/toprope weighting rope)')

    import matplotlib.image as mpimg
    from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
    from scipy import ndimage
    artists = []
    photo = mpimg.imread('animation/photos/20210704_160700.jpg')
    photo = ndimage.rotate(photo, -90)
    imagebox = OffsetImage(photo, zoom=0.1)
    ab = AnnotationBbox(imagebox, (8, 7))
    photo_map = {
        'Start':
        mpimg.imread('animation/photos/20210509_092007.jpg'),
        'Cloaca':
        ndimage.rotate(mpimg.imread('animation/photos/20210511_131111.jpg'),
                       -90),
        'ScarIet Sage':
        mpimg.imread('animation/photos/scarlet_sage.png'),
        'Diapason':
        ndimage.rotate(mpimg.imread('animation/photos/20210511_155128.jpg'),
                       -90),
        'Diapason2':
        mpimg.imread('animation/photos/20210511_155129.jpg'),
        'Tiptoe Ridge':
        ndimage.rotate(mpimg.imread('animation/photos/20210512_090702.jpg'),
                       -90),
        'Piccolo':
        ndimage.rotate(mpimg.imread('animation/photos/20210513_113415.jpg'),
                       -90),
        'Piccolo2':
        mpimg.imread('animation/photos/20210513_113643.jpg'),
        'Mantle':
        ndimage.rotate(mpimg.imread('animation/photos/20210704_133931.jpg'),
                       -90),
        'Mantle2':
        mpimg.imread('animation/photos/20210704_160639(0).jpg'),
        'Mantle3':
        mpimg.imread('animation/photos/20210704_160700.jpg')
    }
    df['photo'] = df.apply(lambda x: photo_map[x['Ascent Label']]
                           if x['Ascent Label'] in photo_map else None,
                           axis=1)
    """
    artists.append([ab])
    #photo = mpimg.imread('animation/photos/20210511_131111.jpg')
    #photo = ndimage.rotate(photo, -90)
    #imagebox = OffsetImage(photo, zoom=0.1)
    #ab = AnnotationBbox(imagebox, (8, 7))
    #artists.append([ab])
    #ax.add_artist(ab)
    #ax.imshow(photo)
    ax2 = fig.add_axes([0.3, 0.2, 0.7, 0.3])
    ims = []
    im = ax2.imshow(photo)
    ims.append([im])
    photo = mpimg.imread('animation/photos/20210511_131111.jpg')
    photo = ndimage.rotate(photo, -90)
    im = ax2.imshow(photo, animated=True)
    ims.append([im])
    print(ims)




    ani = animation.ArtistAnimation(fig, ims, interval=1000, blit=True)
    """

    #width, height = photo.shape[0], photo.shape[1]
    #ax2 = fig.add_axes([0.4, 0.4, 0.00010*width, 0.00010*height])
    #ax2.tick_params(left=False,
    #                bottom=False)
    #ax2.set(xticklabels=[], yticklabels=[])
    #ax2.imshow(photo, aspect='auto')

    photo = photo_map['Start']
    width, height = photo.shape[0], photo.shape[1]
    ax3 = fig.add_axes([0.4, 0.2, 0.00016 * height, 0.00016 * width])
    ax3.tick_params(left=False, bottom=False)
    ax3.set(xticklabels=[], yticklabels=[])
    ax3.axis('off')
    ax3.imshow(photo)

    _ = ax.legend(
        [clean_seconds_barh, clean_topropes_barh, battle_to_top_barh],
        ['clean seconds', 'clean topropes', 'weighted rope'],
        loc='center',
        bbox_to_anchor=(0.5, -0.10),
        shadow=False,
        ncol=3)

    def prepare_animation(trad_onsights_barh):
        def animate(frame_number):
            photo = df.iloc[frame_number - 1].photo
            if photo is not None:
                width, height = photo.shape[0], photo.shape[1]
                ax3.imshow(photo)
            print(frame_number)
            counts = get_ascent_counts(df.iloc[:frame_number])
            print(counts)
            trad_onsights_barh_new = ax.barh(range(1, 25),
                                             counts['trad_onsights'],
                                             color='green',
                                             label='Trad onsight')
            trad_onsights_barh.patches = trad_onsights_barh_new.patches
            sum_ = copy.copy(counts['trad_onsights'])
            sport_onsights_barh_new = ax.barh(range(1, 25),
                                              counts['sport_onsights'],
                                              left=sum_,
                                              color='#98ff98',
                                              label='Sport onsight')
            sport_onsights_barh.patches = sport_onsights_barh_new.patches
            sum_ += counts['sport_onsights']
            trad_flashes_barh_new = ax.barh(range(1, 25),
                                            counts['trad_flashes'],
                                            left=sum_,
                                            color='#800020',
                                            label='Trad flash')
            trad_flashes_barh.patches = trad_flashes_barh_new.patches
            sum_ += counts['trad_flashes']
            #ax.barh_new(range(1, 25), sport_flashes, left = trad_onsights + sport_onsights + trad_flashes, color='orange')
            trad_redpoints_barh_new = ax.barh(range(1, 25),
                                              counts['trad_redpoints'],
                                              left=sum_,
                                              color='red',
                                              label='Trad redpoint')
            trad_redpoints_barh.patches = trad_redpoints_barh_new.patches
            sum_ += counts['trad_redpoints']
            #ax.barh_new(range(1, 25), sport_redpoints, left = trad_onsights + sport_onsights + trad_flashes + sport_flashes + trad_redpoints, color='#FF00FF')
            pinkpoints_barh_new = ax.barh(range(1, 25),
                                          counts['pinkpoints'],
                                          left=sum_,
                                          color='pink',
                                          label='Pinkpoint (sport or trad)')
            pinkpoints_barh.patches = pinkpoints_barh_new.patches
            sum_ += counts['pinkpoints']
            cleans_barh_new = ax.barh(range(1, 25),
                                      counts['cleans'],
                                      left=sum_,
                                      color='xkcd:sky blue',
                                      label='Clean lead (yoyo, simulclimbing)')
            cleans_barh.patches = cleans_barh_new.patches
            sum_ += counts['cleans']
            clean_seconds_barh_new = ax.barh(range(1, 25),
                                             counts['clean_seconds'],
                                             left=sum_,
                                             color='#FFA500',
                                             label='Clean second')
            clean_seconds_barh.patches = clean_seconds_barh_new.patches
            sum_ += counts['clean_seconds']
            clean_topropes_barh_new = ax.barh(range(1, 25),
                                              counts['clean_topropes'],
                                              left=sum_,
                                              color='#FFFF00',
                                              label='Clean toprope')
            clean_topropes_barh.patches = clean_topropes_barh_new.patches
            sum_ += counts['clean_topropes']
            battle_to_top_barh_new = ax.barh(
                range(1, 25),
                counts['battle_to_top'],
                left=sum_,
                color='gray',
                label='Battle to top (hangdog, second/toprope weighting rope)')
            battle_to_top_barh.patches = battle_to_top_barh_new.patches
            if frame_number > 0:
                ax.set_title(f'{df.iloc[frame_number-1]["Ascent Label"]}',
                             fontsize=40)

        return animate

    ani = animation.FuncAnimation(fig,
                                  prepare_animation(trad_onsights_barh),
                                  len(df) + 1,
                                  repeat=False,
                                  interval=2500)

    tag = ani.to_html5_video()
    with open('tag.html', 'w') as f:
        print(tag, file=f)

    plt.show()
Beispiel #8
0
def main(config):

    np.random.seed(config.random_seed)

    # ensure directories are setup
    prepare_dirs(config)

    # load data


    with h5py.File('data4torch.h5', 'r') as hf:
        X_train = hf['data'][:]

    with h5py.File('data4torch.h5', 'r') as hf:
        y_train = hf['labels'][:]


    # convert image data to float64 matrix. float64 is need for bh_sne
    X_train = np.asarray(X_train).astype('float64')    

    # shuffle dataset
    if config.shuffle:
        p = np.random.permutation(len(X_train))
        X_train = X_train[p]
        y_train = y_train[p]

    num_classes = len(np.unique(y_train))
    labels = np.arange(num_classes)

    # restrict to a sample because slow
    mask = np.arange(config.num_samples)
    X_sample = X_train[mask].squeeze()
    y_sample = y_train[mask]

    # grab file names for saving
    file_name = name_file(config) + '.p'
    v = '_v1'
    if config.with_images == True:
        v = '_v2'
    img_name = name_file(config) + v + '.pdf'

    if config.compute_embeddings:
        print("X_sample: {}".format(X_sample.shape))
        print("y_sample: {}".format(y_sample.shape))

        # flatten images to (N, D) for feeding to t-SNE
        X_sample_flat = np.reshape(X_sample, [X_sample.shape[0], -1])

        # compute tsne embeddings
        embeddings = TSNE(n_components=config.num_dimensions, init='pca', verbose=2).fit_transform(X_sample_flat)

        # dump
        pickle.dump(embeddings, open(config.data_dir + file_name, "wb"))

    # else load
    print("Loading embedding...")
    embeddings = pickle.load(open(config.data_dir + file_name, "rb"))

    print('Plotting...')
    if config.num_dimensions == 3:

        # safeguard
        if config.with_images == True:
            sys.exit("Cannot plot images with 3D plots.")

        fig = plt.figure()
        ax = fig.add_subplot(111, projection='3d')
        colors = cm.Spectral(np.linspace(0, 1, num_classes))

        xx = embeddings[:, 0]
        yy = embeddings[:, 1]
        zz = embeddings[:, 2]

        # plot the 3D data points
        for i in range(num_classes):
            ax.scatter(xx[y_sample==i], yy[y_sample==i], zz[y_sample==i], color=colors[i], label=labels[i], s=10)

        ax.xaxis.set_major_formatter(NullFormatter())
        ax.yaxis.set_major_formatter(NullFormatter())
        ax.zaxis.set_major_formatter(NullFormatter())
        plt.axis('tight')
        plt.legend(loc='best', scatterpoints=1, fontsize=5)
        plt.savefig(config.plot_dir + img_name, format='pdf', dpi=600)
        plt.show()

    # 2D plot
    else:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        colors = cm.Spectral(np.linspace(0, 1, num_classes))

        xx = embeddings[:, 0]
        yy = embeddings[:, 1]

        # plot the images
        if config.with_images == True:
            for i, (x, y) in enumerate(zip(xx, yy)):
                im = OffsetImage(X_sample[i], zoom=0.1, cmap='gray')
                ab = AnnotationBbox(im, (x, y), xycoords='data', frameon=False)
                ax.add_artist(ab)
            ax.update_datalim(np.column_stack([xx, yy]))
            ax.autoscale()

        # plot the 2D data points
        for i in range(num_classes):
            ax.scatter(xx[y_sample==i], yy[y_sample==i], color=colors[i], label=labels[i], s=10)

        ax.xaxis.set_major_formatter(NullFormatter())
        ax.yaxis.set_major_formatter(NullFormatter())
        plt.axis('tight')
        plt.legend(loc='best', scatterpoints=1, fontsize=5)
        plt.savefig(config.plot_dir + img_name, format='pdf', dpi=600)
        plt.show()
 def __getImage(path):
     return OffsetImage(plt.imread(path), zoom=0.075)
Beispiel #10
0
clusterer = KMeans
clusterer_instance = clusterer(2, EuclideanDistance())
clusterer_instance.train(features)
labels = clusterer_instance.apply().get_labels()
print labels

print 'applied %s, took %fs' % (converter_instance.get_name(), end - start)
print 'plotting'

fig = figure()
ax = fig.add_subplot(111, axisbg='#ffffff')
ax.scatter(new_features[0], new_features[1], color='black')
import random
for i in range(len(new_features[0])):
    feature_vector = features.get_feature_vector(i)
    Z = zeros([nd, md, 4])
    Z[:, :, 0] = 255 - feature_vector.reshape(nd, md)[::-1, :]
    Z[:, :, 1] = Z[:, :, 0]
    Z[:, :, 2] = Z[:, :, 0]
    for k in range(nd):
        for j in range(md):
            Z[k, j, 3] = pow(sin(k * pi / nd) * sin(j * pi / md), 0.5)
    imagebox = OffsetImage(Z, cmap=cm.gray, zoom=0.25)
    ab = AnnotationBbox(imagebox, (new_features[0, i], new_features[1, i]),
                        pad=0.001,
                        frameon=False)
    ax.add_artist(ab)
axis('off')
savefig('faces.png')
show()
Beispiel #11
0
def getImage(path):
    return OffsetImage(plt.imread(path))
Beispiel #12
0
def test_annotationbbox_extents():
    plt.rcParams.update(plt.rcParamsDefault)
    fig, ax = plt.subplots(figsize=(4, 3), dpi=100)

    ax.axis([0, 1, 0, 1])

    an1 = ax.annotate("Annotation",
                      xy=(.9, .9),
                      xytext=(1.1, 1.1),
                      arrowprops=dict(arrowstyle="->"),
                      clip_on=False,
                      va="baseline",
                      ha="left")

    da = DrawingArea(20, 20, 0, 0, clip=True)
    p = mpatches.Circle((-10, 30), 32)
    da.add_artist(p)

    ab3 = AnnotationBbox(da, [.5, .5],
                         xybox=(-0.2, 0.5),
                         xycoords='area_data',
                         boxcoords="axes fraction",
                         box_alignment=(0., .5),
                         arrowprops=dict(arrowstyle="->"))
    ax.add_artist(ab3)

    im = OffsetImage(np.random.rand(10, 10), zoom=3)
    im.image.axes = ax
    ab6 = AnnotationBbox(im, (0.5, -.3),
                         xybox=(0, 75),
                         xycoords='axes fraction',
                         boxcoords="offset points",
                         pad=0.3,
                         arrowprops=dict(arrowstyle="->"))
    ax.add_artist(ab6)

    fig.canvas.draw()
    renderer = fig.canvas.get_renderer()

    # Test Annotation
    bb1w = an1.get_window_extent(renderer)
    bb1e = an1.get_tightbbox(renderer)

    target1 = [332.9, 242.8, 467.0, 298.9]
    assert_allclose(bb1w.extents, target1, atol=2)
    assert_allclose(bb1e.extents, target1, atol=2)

    # Test AnnotationBbox
    bb3w = ab3.get_window_extent(renderer)
    bb3e = ab3.get_tightbbox(renderer)

    target3 = [-17.6, 129.0, 200.7, 167.9]
    assert_allclose(bb3w.extents, target3, atol=2)
    assert_allclose(bb3e.extents, target3, atol=2)

    bb6w = ab6.get_window_extent(renderer)
    bb6e = ab6.get_tightbbox(renderer)

    target6 = [180.0, -32.0, 230.0, 92.9]
    assert_allclose(bb6w.extents, target6, atol=2)
    assert_allclose(bb6e.extents, target6, atol=2)

    # Test bbox_inches='tight'
    buf = io.BytesIO()
    fig.savefig(buf, bbox_inches='tight')
    buf.seek(0)
    shape = plt.imread(buf).shape
    targetshape = (350, 504, 4)
    assert_allclose(shape, targetshape, atol=2)

    # Simple smoke test for tight_layout, to make sure it does not error out.
    fig.canvas.draw()
    fig.tight_layout()
    fig.canvas.draw()
def road_user_icon_counts(title,
                          car,
                          bike,
                          pedestrian,
                          save_path,
                          textcolor='#000000',
                          facecolor='#FFFFFF',
                          iconpath=None):
    """
    car, bike, pedestrian: str or int, the desired data to display under these different road users

    Example:
    road_user_icon_counts(title='Road User Counts', car=10, bike='bike', pedestrian=0, save_path='out.png')
    """
    dpi = 100.0
    mpl_width, mpl_height = (10, 8)

    # make figure without frame
    fig = plt.figure(frameon=False)
    fig.set_size_inches(mpl_width, mpl_height)
    ax = fig.add_subplot(111)

    # hide axis
    ax.set_axis_off()

    # set your axis size
    ax.axis([0, mpl_width, 0, mpl_height])

    fontsize = 30

    # Title
    title_y = 0.85
    ax.text(0.5 * mpl_width,
            title_y * mpl_height,
            str(title),
            horizontalalignment='center',
            fontsize=fontsize,
            color=textcolor)

    car_loc = 0.15
    bike_loc = 0.5
    ped_loc = 0.85
    icon_y = 0.6
    text_y = 0.4

    if iconpath is None:
        # assumes that the icon image files are in the same directory as this file
        iconpath = os.path.dirname(os.path.abspath(__file__))

    # car icon
    fn = os.path.join(iconpath, 'car.png')
    arr_img = plt.imread(fn, format='png')
    im = OffsetImage(arr_img, zoom=0.7)
    ab = AnnotationBbox(im, (car_loc * mpl_width, icon_y * mpl_height),
                        xycoords='data',
                        frameon=False)
    ax.add_artist(ab)
    # car count
    ax.text(car_loc * mpl_width,
            text_y * mpl_height,
            str(car),
            horizontalalignment='center',
            fontsize=fontsize,
            color=textcolor)

    # bike icon
    fn = os.path.join(iconpath, 'bike.png')
    arr_img = plt.imread(fn, format='png')
    im = OffsetImage(arr_img, zoom=0.7)
    ab = AnnotationBbox(im, (bike_loc * mpl_width, icon_y * mpl_height),
                        xycoords='data',
                        frameon=False)
    ax.add_artist(ab)
    # bike count
    ax.text(bike_loc * mpl_width,
            text_y * mpl_height,
            str(bike),
            horizontalalignment='center',
            fontsize=fontsize,
            color=textcolor)

    # ped icon
    fn = os.path.join(iconpath, 'pedestrian.png')
    arr_img = plt.imread(fn, format='png')
    im = OffsetImage(arr_img, zoom=0.7)
    ab = AnnotationBbox(im, (ped_loc * mpl_width, icon_y * mpl_height),
                        xycoords='data',
                        frameon=False)
    ax.add_artist(ab)
    # bike count
    ax.text(ped_loc * mpl_width,
            text_y * mpl_height,
            str(pedestrian),
            horizontalalignment='center',
            fontsize=fontsize,
            color=textcolor)

    fig.savefig(save_path,
                dpi=dpi,
                bbox_inches=0,
                pad_inches=0,
                facecolor=facecolor,
                format='jpg')
    plt.close()
Beispiel #14
0
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
import numpy as np

# plotting the graph
fig, ax = plt.subplots()

x = np.linspace(0, 10, 20)
y = np.cos(x)
ax.set_title('Cosine Values', fontsize=15)
ax.set_xlabel('Value')
ax.set_ylabel('Cosine')

# reading the image
image = plt.imread('emoji.png')  #😍

# OffsetBox
image_box = OffsetImage(image, zoom=0.1)

# creating annotation for each point
# on the graph
x, y = np.atleast_1d(x, y)

# for each value of (x,y), we create
# an annotation
for x0, y0 in zip(x, y):
    ab = AnnotationBbox(image_box, (x0, y0), frameon=False)
    ax.add_artist(ab)

ax.plot(x, y, c='green')
plt.show()
Beispiel #15
0
def test_model():

    # Load pre-trained parameters
    #datafile = open(dataset_name + '/srbm.pkl', 'r')
    #srbm = cPickle.load(datafile)
    #datafile.close()

    sRBM = stackedRBMs(params_file=dataset_name + '/srbm.pkl', input=x)

    test = theano.function(
        inputs=[index],
        outputs=[sRBM.get_cost_sqr(),
                 sRBM.fprop(),
                 sRBM.get_code()],
        givens={x: test_x_shared[index * Nt:(index + 1) * Nt]})

    test_error, test_recon, test_code = test(0)
    print test_error
    img = Image.fromarray(
        tile_raster_images(X=test_recon,
                           img_shape=(28, 28),
                           tile_shape=(100, 100)))
    img.save(dataset_name + '/recon.png')

    rs = cm.rainbow(np.linspace(0, 1, 10))
    print test_code.shape
    for i in range(10):
        ix = test_code[np.where(test_set[1] == i)]
        #print ix
        plt.scatter(ix[:, 0], ix[:, 1], color=rs[i])
    #test_set[1]
    plt.savefig(dataset_name + '/clusters.png')

    ax = plt.gca()
    artists = []
    zoom = 0.1
    datax = test_set[0]
    fig, ax = plt.subplots()
    for i in range(len(test_set[0])):
        #inds = np.where(test_set[1] == i)
        #ix = test_code[inds]
        #print ix
        #imscatter(ix[:,0], ix[:,1], datax, zoom = 0.5, ax = ax, artists = artists)
        #x_ = ix[:,0]
        #y_ = ix[:,1]
        #i = 0
        #for x0, y0 in zip(x_, y_):

        img_plane = np.ones(datax[i].shape)[np.newaxis]
        #img = Image.fromarray(tile_raster_images(X=(1 - datax[i][np.newaxis],None,None,None),img_shape=(28,28),tile_shape=(1,1)))
        channel = 1 - datax[i][np.newaxis]
        img = Image.fromarray(
            tile_raster_images(X=(channel, channel, channel, 1 - channel),
                               img_shape=(28, 28),
                               tile_shape=(1, 1)))
        #img = Image.fromarray(channel_image(X=1 - datax[i][np.newaxis],img_shape=(28,28),tile_shape=(1,1)))
        img.save('test.png')
        img = plt.imread(
            get_sample_data('/home/llajan/RBM/from_scratch/test.png'))
        im = OffsetImage(img, zoom=zoom)
        ab = AnnotationBbox(im, (test_code[i][0], test_code[i][1]),
                            xycoords='data',
                            frameon=False)
        artists.append(ax.add_artist(ab))
    ax.update_datalim(np.column_stack([test_code[:, 0], test_code[:, 1]]))
    ax.autoscale()

    #ax.scatter(ix[:,0],ix[:,1])
    #plt.scatter(ix[:,0],ix[:,1],color=rs[i])
    #test_set[1]
    plt.savefig(dataset_name + '/clusters1.eps', format='eps', dpi=1000)
def plot_data(data, filename='plot.png',maxups=None,maxcoms=None,maxage=None,show=False, timeline = None):
    '''
    Where the plotting magic happens.
    plot_data works on a data point. It can be used directly after get_data.
    After collect_data, plot_collec should be preferred, to correctly handle the max... args.
    If max... args are None, plot_data will freely adapt the chart and color.

    timeline contains specific data from plot_collec and is required to plot the upper timeline.
    Plotting the timeline requires a full knowledge of the data_collec and therefore
    doesnt work on a single data.
    '''
    def format_title(title,post_sub,analysed_sub,limit_title_len):
        '''reformat the title if too long and add the sub name if different from
        the analysed sub'''
        if post_sub != 'r/'+analysed_sub:
            f_title = post_sub + ' - ' + title
        else:
            f_title = title
        if len(f_title) > limit_title_len:
            f_title = f_title[:limit_title_len-3]+'...'
        return f_title

    def crop_image(img, imgheight):
        '''cut the thumbnail in the middle of the height'''
        topcut = round(len(img)/2) - round(imgheight/2)
        bottomcut = round(len(img)/2) + round(imgheight/2)
        img = img[topcut:bottomcut, :, :]
        return img

    def make_colormap_age(maxage,ages,cmapname='GnBu'):
        '''prepare the colormap'''
        cmap = plt.cm.get_cmap(cmapname)
        norm = matplotlib.colors.Normalize(vmin=0, vmax=1.05*maxage)
        #avoid that vmax matches the max of the color map, otherwise
        #it could be white with certain cmaps
        sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
        sm.set_array([])
        cmapage = []
        for age in ages:
            cmapage.append(cmap(norm(age)))
        return cmapage, sm

    def rm_frames(ax):
        '''shortcut to remove all frames of a subplot'''
        ax.spines['left'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.spines['bottom'].set_visible(False)

    imgheight = 48 #crop images at 50px high (108px width by default)
    limit_title_len = 60 #max nbr of characters in displayed title
    figsize = (18,10)
    ups = data['ups']
    coms = data['coms']
    thumbs = data['thumbs']
    ages = [age/60 for age in data['ages']]
    titles = data['titles']
    subs = data['subs']
    if not maxage:
        maxage = max(ages)
    maxage = maxage/60
    cmapage, sm = make_colormap_age(maxage=maxage,ages=ages)
    maxposts = len(ups)
    list_yticks = list(range(1,maxposts+1))

    #initiate plot
    plt.rcdefaults()
    matplotlib.rcParams.update({'font.size': 15})
    plt.yticks(list_yticks)
    fig = plt.figure(figsize = figsize)
    gs = gridspec.GridSpec(2, 5, width_ratios=[0.2,1.5,0.3,1.5,0.05], height_ratios=[1,5])
    #Grid is 2 rows * 4 columns
    #Top row is for the timeline
    #Bottom row is for karma bars / thumbnails / comments bars / colormap legend

    #top of the plot, where the timeline is plotted

    if timeline:
        color_ups = '#549ED6'
        color_coms = '#33cc33'
        ax_tl = plt.subplot(gs[0,1:5])
        rm_frames(ax_tl)
        ax_tl.spines['bottom'].set_visible(True)
        tl_ups = timeline['ups']
        tl_coms = timeline['coms']
        tl_ages = [age/60 for age in timeline['ages']]
        tl_dates = timeline['dates']
        curr_date = datetime.strptime(data['timestamp'],"%b %d %Y %H:%M:%S")
        idx_curr_date = tl_dates.index(curr_date)
        ax_tl.plot(tl_dates[:idx_curr_date+1],tl_ups[:idx_curr_date+1],color=color_ups)
        ax_tl.plot(tl_dates[idx_curr_date:],tl_ups[idx_curr_date:],color=color_ups, alpha=0.1)
        ax_tl.set_ylabel('mean(Karma)', color=color_ups)
        ax_tl.tick_params('y', colors=color_ups)
        ax_tl.yaxis.set_major_locator(mticker.LinearLocator(3))
        ax_tl.yaxis.grid(color='grey', linestyle='-', linewidth=0.5, alpha=0.5)
        ax_tltwin = ax_tl.twinx()
        rm_frames(ax_tltwin)
        ax_tltwin.plot(tl_dates[:idx_curr_date+1],tl_ages[:idx_curr_date+1],color=color_coms)
        ax_tltwin.plot(tl_dates[idx_curr_date:],tl_ages[idx_curr_date:],color=color_coms, alpha=0.1)
        ax_tltwin.set_ylabel('mean(ages in hour)', color=color_coms)
        ax_tltwin.yaxis.set_major_formatter(mticker.FormatStrFormatter('%.1f'))
        ax_tltwin.tick_params('y', colors=color_coms)
        ax_tltwin.yaxis.set_major_locator(mticker.LinearLocator(3))
        #ax_tltwin.xaxis.set_major_locator(mdates.HourLocator())
        ax_tltwin.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))
    else: #if no timeline, when plot_data is used on a single data point, fill
          #the empty space with a title.
          #TODO: improve that part to make better use of the space...
        ax_tl = plt.subplot(gs[0,1:])
        ax_tl.axis('off')
        text_title = 'r/' + data['sub'] + ' - ' + data['timestamp']
        ax_tl.text(0.4,0.5,text_title,fontsize=16, fontweight='bold')

    #left side of the plot, where the karma is plotted
    ax_ups = plt.subplot(gs[1,:2])
    rm_frames(ax_ups)
    if maxups:
        ax_ups.set_xlim(0, maxups)
    ax_ups.barh(list_yticks,ups, color = cmapage)
    ax_ups.invert_xaxis()
    ax_ups.invert_yaxis()
    ax_ups.set_xlabel('Karma')
    ax_ups.xaxis.set_label_position('bottom')
    ax_ups.xaxis.tick_bottom()
    ax_ups.set_yticks([])
    plt.setp(ax_ups.get_yticklabels(), visible=False)
    ax_ups.xaxis.grid(color='grey', linestyle='-', linewidth=0.5, alpha=0.5)
    for n in range(len(titles)):
        title = format_title(titles[n],subs[n],data['sub'],limit_title_len)
        title_pos = ax_ups.get_xlim()[0]
        ax_ups.text(title_pos,n+1,' '+title, verticalalignment='center')

    #center of the plot, for pictures
    ax_thumbs = plt.subplot(gs[1,2], sharey=ax_ups)
    ax_thumbs.set_yticklabels([])
    ax_thumbs.axis('off')
    for n in range(len(thumbs)):
        arr_img = crop_image(img=matplotlib.image.imread(thumbs[n]),imgheight=imgheight)
        imagebox = OffsetImage(arr_img, 0.7)
        ab = AnnotationBbox(imagebox, (0.5, n+1), frameon=False)
        ax_thumbs.add_artist(ab)

    #right side of the plot, where the comments are plotted
    ax_coms = plt.subplot(gs[1,3], sharey=ax_ups)
    rm_frames(ax_coms)
    if maxcoms:
        ax_coms.set_xlim(0,maxcoms)
    ax_coms.barh(list_yticks,coms, color = cmapage)
    ax_coms.set_xlabel('Comments')
    plt.setp(ax_coms.get_yticklabels(), visible=False)
    ax_coms.xaxis.set_label_position('bottom')
    ax_coms.xaxis.tick_bottom()
    ax_coms.xaxis.grid(color='grey', linestyle='-', linewidth=0.5, alpha=0.5)

    #colormap legend
    ax_cbar = plt.subplot(gs[1,4])
    cbar = plt.colorbar(sm, cax = ax_cbar)
    cbar.set_label('age in hours')
    plt.subplots_adjust(wspace=0.05, hspace=0.2)
    #Check existence of plots directory
    if not os.path.exists("plots/"):
        os.makedirs("plots/")
    plt.savefig('plots/'+filename, bbox_inches='tight')
    if show: plt.show()
    plt.close()
    return
def plot(dset_city):
    city = dset_city.attrs['city']
    print_message('Producing meteogram for %s' % city)
    time, run, cum_hour = get_time_run_cum(dset_city)
    t = dset_city['t']
    t.metpy.convert_units('degC')
    rh = dset_city['r']
    t2m = dset_city['2t']
    t2m.metpy.convert_units('degC')
    td2m = dset_city['2d']
    td2m.metpy.convert_units('degC')
    vmax_10m = dset_city['VMAX_10M']
    vmax_10m.metpy.convert_units('kph')
    pmsl = dset_city['prmsl']
    pmsl.metpy.convert_units('hPa')
    plevs = dset_city['t'].metpy.vertical.metpy.unit_array.to('hPa').magnitude

    rain_acc = dset_city['RAIN_GSP'] + dset_city['RAIN_CON']
    snow_acc = dset_city['SNOW_GSP'] + dset_city['SNOW_CON']
    rain = rain_acc.differentiate(coord="time", datetime_unit="h")
    snow = snow_acc.differentiate(coord="time", datetime_unit="h")

    weather_icons = get_weather_icons(dset_city['WW'], time)

    fig = plt.figure(figsize=(10, 12))
    gs = gridspec.GridSpec(4, 1, height_ratios=[3, 1, 1, 1])

    ax0 = plt.subplot(gs[0])
    cs = ax0.contourf(time,
                      plevs,
                      t.T,
                      extend='both',
                      cmap=get_colormap("temp"),
                      levels=np.arange(-70, 35, 5))
    ax0.axes.get_xaxis().set_ticklabels([])
    ax0.invert_yaxis()
    ax0.set_ylim(1000, 200)
    ax0.set_xlim(time[0], time[-1])
    ax0.set_ylabel('Pressure [hPa]')
    y_labels = ax0.get_yticks()
    cbar_ax = fig.add_axes([0.92, 0.55, 0.02, 0.3])
    cmap_new = truncate_colormap(plt.get_cmap('gray_r'), 0.1, 0.6)
    cs2 = ax0.contour(time,
                      plevs,
                      rh.T,
                      levels=[25, 50, 100],
                      cmap=cmap_new,
                      alpha=0.7)
    labels = ax0.clabel(cs2, cs2.levels, inline=True, fmt='%4.0f', fontsize=6)

    dset_winds = dset_city.sel(
        time=pd.date_range(time[0], time[-1], freq='6H'))
    v = ax0.barbs(pd.to_datetime(dset_winds.time.values),
                  plevs,
                  dset_winds['u'].T,
                  dset_winds['v'].T,
                  alpha=0.3,
                  length=5.5)
    ax0.xaxis.set_major_locator(mdates.HourLocator(interval=6))
    ax0.grid(True, alpha=0.5)
    an_fc = annotation_run(ax0, run)
    an_var = annotation(ax0,
                        'RH, $T$ and winds @(%3.1fN, %3.1fE, %d m)' %
                        (dset_city.lat, dset_city.lon, dset_city.HSURF),
                        loc='upper left')
    an_city = annotation(ax0, city, loc='upper center')

    ax1 = plt.subplot(gs[1])
    ax1.set_xlim(time[0], time[-1])
    ts = ax1.plot(time, t2m, label='2m $T$', color='darkcyan')
    ts1 = ax1.plot(time,
                   td2m,
                   label='2m $T_d$',
                   color='darkcyan',
                   linestyle='dashed')
    ax1.axes.get_xaxis().set_ticklabels([])
    plt.legend(fontsize=7)
    ax1.set_ylabel('2m $T$, $T_d$ [$^{\circ}$C]')
    ax1.xaxis.set_major_locator(mdates.HourLocator(interval=6))
    ax1.grid(True, alpha=0.5)

    for dt, weather_icon, dewp in zip(time, weather_icons, t2m):
        imagebox = OffsetImage(weather_icon, zoom=.025)
        ab = AnnotationBbox(imagebox, (mdates.date2num(dt), dewp),
                            frameon=False)
        ax1.add_artist(ab)

    ax2 = plt.subplot(gs[2])
    ax2.set_xlim(time[0], time[-1])
    ts = ax2.plot(time, vmax_10m, label='Gusts', color='lightcoral')
    ax2.set_ylabel('Wind gust [km/h]')
    ax22 = ax2.twinx()
    ts1 = ax22.plot(time, pmsl, label='MSLP', color='m')
    ax2.axes.get_xaxis().set_ticklabels([])
    ax22.set_ylabel('MSLP [hPa]')
    ax2.xaxis.set_major_locator(mdates.HourLocator(interval=6))
    ax2.grid(True, alpha=0.5)

    # Collect all the elements for the legend
    handles, labels = [], []
    for ax in (ax2, ax22):
        for h, l in zip(*ax.get_legend_handles_labels()):
            handles.append(h)
            labels.append(l)
    plt.legend(handles, labels, fontsize=7)

    ax3 = plt.subplot(gs[3])
    ax3.set_xlim(time[0], time[-1])
    ts = ax3.plot(time,
                  rain_acc,
                  label='Rain (acc.)',
                  color='dodgerblue',
                  linewidth=0.1)
    ts1 = ax3.plot(time,
                   snow_acc,
                   label='Snow (acc.)',
                   color='orchid',
                   linewidth=0.1)
    ax3.fill_between(time, rain_acc, y2=0, facecolor='dodgerblue', alpha=0.2)
    ax3.fill_between(time, snow_acc, y2=0, facecolor='orchid', alpha=0.2)
    ax3.set_ylim(bottom=0)
    ax3.set_ylabel('Accum. [mm]')
    ax33 = ax3.twinx()
    ts2 = ax33.plot(time, rain, label='Rain', color='dodgerblue')
    ts3 = ax33.plot(time, snow, label='Snow', color='orchid')
    ax33.set_ylim(bottom=0)
    ax33.set_ylabel('Inst. [mm h$^{-1}$]')
    ax33.legend(fontsize=7)

    ax3.grid(True, alpha=0.5)
    ax3.xaxis.set_major_locator(mdates.HourLocator(interval=6))
    ax3.xaxis.set_major_formatter(DateFormatter('%d %b %HZ'))
    for tick in ax3.get_xticklabels():
        tick.set_rotation(45)
        tick.set_horizontalalignment('right')

    fig.subplots_adjust(hspace=0.1)
    fig.colorbar(cs,
                 orientation='vertical',
                 label='Temperature [C]',
                 cax=cbar_ax)

    # Build the name of the output image
    filename = folder_images + '/meteogram_%s.png' % city
    plt.savefig(filename, dpi=100, bbox_inches='tight')
    plt.clf()
def dibujar_tablero(f, n):
    # Visualiza un tablero dada una formula f
    # Input:
    #   - f, una lista de literales
    #   - n, un numero de identificacion del archivo
    # Output:
    #   - archivo de imagen tablero_n.png

    # Inicializo el plano que contiene la figura
    fig, axes = plt.subplots()
    axes.get_xaxis().set_visible(False)
    axes.get_yaxis().set_visible(False)

    # Dibujo el tablero
    step = 1. / 4
    tangulos = []
    # Creo los cuadrados en el tablero

    tangulos.append(patches.Rectangle(*[(0, 0), step, step, step]))
    tangulos.append(patches.Rectangle(*[(0, step), step, step, step]))
    tangulos.append(patches.Rectangle(*[(0, 2 * step), step, step, step]))
    tangulos.append(patches.Rectangle(*[(0, 3 * step), step, step, step]))

    tangulos.append(patches.Rectangle(*[(step, 0), step, step, step]))
    tangulos.append(patches.Rectangle(*[(step, step), step, step, step]))
    tangulos.append(patches.Rectangle(*[(step, 2 * step), step, step, step]))
    tangulos.append(patches.Rectangle(*[(step, 3 * step), step, step, step]))

    tangulos.append(patches.Rectangle(*[(2 * step, 0), step, step, step]))
    tangulos.append(patches.Rectangle(*[(2 * step, step), step, step, step]))
    tangulos.append(
        patches.Rectangle(*[(2 * step, 2 * step), step, step, step]))
    tangulos.append(
        patches.Rectangle(*[(2 * step, 3 * step), step, step, step]))

    tangulos.append(patches.Rectangle(*[(3 * step, 0), step, step, step]))
    tangulos.append(patches.Rectangle(*[(3 * step, step), step, step, step]))
    tangulos.append(
        patches.Rectangle(*[(3 * step, 2 * step), step, step, step]))
    tangulos.append(
        patches.Rectangle(*[(3 * step, 3 * step), step, step, step]))

    # Creo las líneas del tablero
    for j in range(4):
        locacion = j * step
        # Crea linea horizontal en el rectangulo
        tangulos.append(patches.Rectangle(*[(0, step + locacion), 1, 0.005],\
                facecolor='black'))
        # Crea linea vertical en el rectangulo
        tangulos.append(patches.Rectangle(*[(step + locacion, 0), 0.005, 1],\
                facecolor='black'))

    for t in tangulos:
        axes.add_patch(t)

    # Cargando imagen de caballo
    arr_img = plt.imread("circulo.png", format='png')
    imagebox = OffsetImage(arr_img, zoom=0.02)
    imagebox.image.axes = axes

    # Creando las direcciones en la imagen de acuerdo a literal
    direcciones = {}
    direcciones[1] = [0.12, 0.87]
    direcciones[2] = [0.37, 0.87]
    direcciones[3] = [0.62, 0.87]
    direcciones[4] = [0.87, 0.87]

    direcciones[5] = [0.12, 0.62]
    direcciones[6] = [0.37, 0.62]
    direcciones[7] = [0.62, 0.62]
    direcciones[8] = [0.87, 0.62]

    direcciones[9] = [0.12, 0.37]
    direcciones[10] = [0.37, 0.37]
    direcciones[11] = [0.62, 0.37]
    direcciones[12] = [0.87, 0.37]

    direcciones[13] = [0.12, 0.12]
    direcciones[14] = [0.37, 0.12]
    direcciones[15] = [0.62, 0.12]
    direcciones[16] = [0.87, 0.12]

    for l in f:
        if '-' not in l:
            if l == 'A':
                l = 10
            elif l == 'B':
                l = 11
            elif l == 'C':
                l = 12
            elif l == 'D':
                l = 13
            elif l == 'E':
                l = 14
            elif l == 'F':
                l = 15
            elif l == 'G':
                l = 16
            ab = AnnotationBbox(imagebox, direcciones[int(l)], frameon=False)
            axes.add_artist(ab)

    # plt.show()
    d = 'Soluciones/'
    try:
        os.makedirs(d)
        print "Creando " + d
    except OSError:
        if not os.path.isdir(d):
            raise
    fig.savefig(d + "tablero_" + str(n) + ".png")
    print "Imagenes creadas! Verificar la carpeta " + d
Beispiel #19
0
warm_color_map = plt.cm.YlOrRd_r

joint_shot_chart = sns.jointplot(shot_df.LOC_X, shot_df.LOC_Y, stat_func=None,
                                kind='kde', space=0, color=warm_color_map(0.1),
                                cmap=warm_color_map, n_levels=50)
joint_shot_chart.fig.set_size_inches(12, 11)

# Draw court onto ax_joint of joint plot
ax = joint_shot_chart.ax_joint
draw_court(ax)

ax.set_xlim(250, -250)
ax.set_ylim(395, -47.5)

# Remove labels and ticks
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')

# Add title and text
ax.set_title('James Harden FGA \n2014-2015 Reg. Season', y=1.2, fontsize=18)
ax.text(-250, 420, 'Data Source: stats.nba.com'
        '\nAuthor: Tiger Shen', fontsize=12)

# Plot Harden image
img = OffsetImage(harden_pic, zoom=0.6)
img.set_offset((625,621)) # Top right corner
ax.add_artist(img)

plt.show()
Beispiel #20
0
def annotate(frame):
    zf = 0.15  #The zoom factor for the image2
    text1 = frame['gt_caption']
    path1 = frame['path']
    words = path1.split('/')
    sim1 = 'class : ' + words[len(words) - 3]
    knn = frame['knn']
    text2 = knn[0]['caption']
    bleu2 = "%.2f" % nltk.translate.bleu_score.sentence_bleu(text1, text2)
    path2 = knn[0]['path']
    words = path2.split('/')
    sim2 = 'class : ' + words[len(words) - 3] + ' Similarity : ' + str(
        knn[0]['similarity']) + ' BLEU :' + str(bleu2)
    text3 = knn[1]['caption']
    bleu3 = "%.2f" % nltk.translate.bleu_score.sentence_bleu(text1, text3)
    path3 = knn[1]['path']
    words = path3.split('/')
    sim3 = 'class : ' + words[len(words) - 3] + ' Similarity: ' + str(
        knn[1]['similarity']) + ' BLEU :' + str(bleu3)
    text4 = knn[2]['caption']
    bleu4 = "%.2f" % nltk.translate.bleu_score.sentence_bleu(text1, text4)
    path4 = knn[2]['path']
    words = path4.split('/')
    sim4 = 'class : ' + words[len(words) - 3] + ' Similarity: ' + str(
        knn[2]['similarity']) + ' BLEU :' + str(bleu4)

    #fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
    fig, ((ax1, ax2, ax3, ax4)) = plt.subplots(4, 1, sharey='row')

    # Define a 1st position to annotate (display it with a marker)
    xy = (0.5, 0.7)
    ax1.plot(xy[0], xy[1], ".r")

    # Annotate the 1st position with a text box ('Test 1')
    offsetbox = TextArea(text1, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax1.add_artist(ab)

    # Annotate the 1st position with a text box ('Test 1')
    offsetbox = TextArea(sim1, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax1.add_artist(ab)

    # Annotate the 1st position with another text box ('Test')
    offsetbox = TextArea(text2, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax2.add_artist(ab)

    offsetbox = TextArea(sim2, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax2.add_artist(ab)

    offsetbox = TextArea(text3, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax3.add_artist(ab)

    offsetbox = TextArea(sim3, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax3.add_artist(ab)

    offsetbox = TextArea(text4, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, 5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax4.add_artist(ab)

    offsetbox = TextArea(sim4, minimumdescent=False)

    ab = AnnotationBbox(offsetbox,
                        xy,
                        xybox=(0.5, -5.5),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))
    ax4.add_artist(ab)

    xy = (1, 0)

    #arr = plt.imread(path1)
    arr = Image.open(path1)
    arr = arr.resize((480, 360), Image.ANTIALIAS)

    im = OffsetImage(arr, zoom=zf)
    im.image.axes = ax1

    ab = AnnotationBbox(im,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax1.add_artist(ab)

    #Adding the second image now
    #arr_img = plt.imread(path2)
    arr_img = Image.open(path2)
    arr_img = arr_img.resize((480, 360), Image.ANTIALIAS)

    imagebox = OffsetImage(arr_img, zoom=zf)
    imagebox.image.axes = ax2

    ab = AnnotationBbox(imagebox,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax2.add_artist(ab)

    #arr_img = plt.imread(path3)
    arr_img = Image.open(path3)
    arr_img = arr_img.resize((480, 360), Image.ANTIALIAS)

    imagebox = OffsetImage(arr_img, zoom=zf)
    imagebox.image.axes = ax2

    ab = AnnotationBbox(imagebox,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax3.add_artist(ab)

    #arr_img = plt.imread(path4)
    arr_img = Image.open(path4)
    arr_img = arr_img.resize((480, 360), Image.ANTIALIAS)

    imagebox = OffsetImage(arr_img, zoom=zf)
    imagebox.image.axes = ax2

    ab = AnnotationBbox(imagebox,
                        xy,
                        xybox=(0.5, 0),
                        xycoords='data',
                        boxcoords=("axes fraction", "data"))

    ax4.add_artist(ab)

    # Fix the display limits to see everything
    ax1.set_ylim(-5, 5)
    ax1.set_xlim(-3, 3)
    ax1.axis('off')
    ax2.set_ylim(-5, 5)
    ax2.set_xlim(-3, 3)
    ax2.axis('off')
    ax3.set_ylim(-5, 5)
    ax3.set_xlim(-3, 3)
    ax3.axis('off')
    ax4.set_ylim(-5, 5)
    ax4.set_xlim(-3, 3)
    ax4.axis('off')
    figure = plt.gcf()  # get current figure
    names = path1.split('/')
    name = str(names[len(names) - 2]) + str(names[len(names) - 1])
    plt.savefig(name + '.png', bbox_inches='tight', dpi=600)
    plt.close()
    im = Image.open(name + '.png')
    os.remove(name + '.png')  #Removing this file as we don't need it
    return im
Beispiel #21
0
def save_pixplot_layout(pixplot_output_folder=None,
                        layout_type="umap",
                        image_zoom=0.1,
                        figsize=(10, 10),
                        dpi=300,
                        transparent=False,
                        filename="test",
                        file_format="png"):
    '''
    Read json files from pix-plot output folder, save layouts as a local image file

    Parameters:

    pixplot_output_folder:
        the "output" folder of pix-plot
    layout_type:
        which type of layout need to save ("umap","umap_jittered","rasterfairy")
    image_zoom:
        zoom the original images to fit the layout size
    figsize:
        tuple, size of the image in inch
    dpi:
        int, dpi of the output image
    transparent:
        boolean, transparancy of image background
    filename:
        string, output name
    file_format:
        string, the format of the image to save (e.g. "jpg","png")

    '''

    # load all layout files from pixplot output folder
    imagelist_root = os.path.join(pixplot_output_folder, "data/imagelists")
    for file in os.listdir(imagelist_root):
        if "imagelist" in file:
            imagelist_file = os.path.join(imagelist_root, file)
    layouts_root = os.path.join(pixplot_output_folder, "data/layouts")
    for file in os.listdir(layouts_root):
        if "umap-jittered" in file:
            umap_jittered_file = os.path.join(layouts_root, file)
        elif "umap" in file:
            umap_file = os.path.join(layouts_root, file)
        elif "rasterfairy" in file:
            rasterfairy_file = os.path.join(layouts_root, file)
    image_folder = os.path.join(pixplot_output_folder, "data/originals")

    # load all image names from imagelist
    with open(imagelist_file) as json_file:
        data = json.load(json_file)
        imagelist = data['images']
    posXlist = []
    posYlist = []

    # save umap layout image
    if layout_type == "umap":
        print("******saving umap******")
        with open(umap_file) as json_file:
            data = json.load(json_file)
            for i in range(len(data)):
                posXlist.append(data[i][0])
                posYlist.append(data[i][1])

        fig = plt.figure(figsize=figsize, dpi=dpi)
        left, bottom, width, height = 0, 0, 1, 1
        ax = fig.add_axes([left, bottom, width, height])

        for j in range(len(imagelist)):
            img = Image.open(image_folder + '/' + imagelist[j])
            imagebox = OffsetImage(img, zoom=image_zoom)
            ab = AnnotationBbox(imagebox, [(posXlist[j] + 1),
                                           (posYlist[j] + 1)],
                                pad=0,
                                frameon=False)
            ax.add_artist(ab)
        plt.xlim(0, 2)
        plt.ylim(0, 2)
        plt.axis('off')
        fig = plt.gcf()

        imagefile = filename + "." + file_format
        fig.savefig(os.path.join(pixplot_output_folder, imagefile),
                    transparent=transparent)
    # save umap_jittered layout image
    elif layout_type == "umap_jittered":
        print("******saving umap_jittered******")
        with open(umap_jittered_file) as json_file:
            data = json.load(json_file)
            for i in range(len(data)):
                posXlist.append(data[i][0])
                posYlist.append(data[i][1])

        fig = plt.figure(figsize=figsize, dpi=dpi)
        left, bottom, width, height = 0, 0, 1, 1
        ax = fig.add_axes([left, bottom, width, height])

        for j in range(len(imagelist)):
            img = Image.open(image_folder + '/' + imagelist[j])
            imagebox = OffsetImage(img, zoom=image_zoom)
            ab = AnnotationBbox(imagebox, [(posXlist[j] + 1),
                                           (posYlist[j] + 1)],
                                pad=0,
                                frameon=False)
            ax.add_artist(ab)
        plt.xlim(0, 2)
        plt.ylim(0, 2)
        plt.axis('off')
        fig = plt.gcf()

        imagefile = filename + "." + file_format
        fig.savefig(os.path.join(pixplot_output_folder, imagefile),
                    transparent=transparent)
    # save rasterfairy layout image
    elif layout_type == "rasterfairy":
        print("******saving rasterfairy******")
        with open(rasterfairy_file) as json_file:
            data = json.load(json_file)
            for i in range(len(data)):
                posXlist.append(data[i][0])
                posYlist.append(data[i][1])

        fig = plt.figure(figsize=figsize, dpi=dpi)
        left, bottom, width, height = 0, 0, 1, 1
        ax = fig.add_axes([left, bottom, width, height])

        for j in range(len(imagelist)):
            img = Image.open(image_folder + '/' + imagelist[j])
            imagebox = OffsetImage(img, zoom=image_zoom)
            ab = AnnotationBbox(imagebox, [(posXlist[j] + 1),
                                           (posYlist[j] + 1)],
                                pad=0,
                                frameon=False)
            ax.add_artist(ab)
        plt.xlim(0, 2)
        plt.ylim(0, 2)
        plt.axis('off')
        fig = plt.gcf()

        imagefile = filename + "." + file_format
        fig.savefig(os.path.join(pixplot_output_folder, imagefile),
                    transparent=transparent)
Beispiel #22
0
axes[1, 1].set_ylabel(r"$D_{KL}$")

axes[1, 0].set_xlabel(r"$T$ [GeV]")
axes[1, 1].set_xlabel(r"$T$ [GeV]")

axes[1, 0].set_xlim([0.135, 0.35])
axes[1, 1].set_xlim([0.135, 0.35])

axes[1, 0].set_ylim([0., 1.4])
axes[1, 1].set_ylim([0., 1.4])

T_ticks = [0.15, 0.2, 0.25, 0.3, 0.35]
axes[1, 0].set_xticks(T_ticks)
axes[1, 1].set_xticks(T_ticks)
fig.align_ylabels()

#im = plt.imread("jetscape_logo.jpeg")
#implot = plt.imshow(im)

im = mpimg.imread('jetscape_logo.jpeg')
imagebox = OffsetImage(im, zoom=0.08)
ab = AnnotationBbox(imagebox, (0.32, 0.8), frameon=False)
axes[1, 0].add_artist(ab)
plt.draw()

plt.tight_layout(True)
plt.subplots_adjust(wspace=0.3, hspace=0.0)
plt.savefig("fig3.png", dpi=400, bbox_inches='tight', pad_inches=0)
plt.savefig("fig3.pdf", bbox_inches='tight', pad_inches=0)
plt.show()
Beispiel #23
0
da = DrawingArea(20, 20, 0, 0)
p = Circle((10, 10), 10)
da.add_artist(p)

ab = AnnotationBbox(da, xy,
                    xybox=(1.02, xy[1]),
                    xycoords='data',
                    boxcoords=("axes fraction", "data"),
                    box_alignment=(0., 0.5),
                    arrowprops=dict(arrowstyle="->"))

ax.add_artist(ab)

# Annotate the 2nd position with an image (a generated array of pixels)
arr = np.arange(100).reshape((10, 10))
im = OffsetImage(arr, zoom=2)
im.image.axes = ax

ab = AnnotationBbox(im, xy,
                    xybox=(-50., 50.),
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.3,
                    arrowprops=dict(arrowstyle="->"))

ax.add_artist(ab)

# Annotate the 2nd position with another image (a Grace Hopper portrait)
fn = get_sample_data("grace_hopper.png", asfileobj=False)
arr_img = plt.imread(fn, format='png')
coordinates, dataList = diffusionMapping(
    data, lambda x, y: math.exp(-LA.norm(x - y) / 1024), 1, dim=2)
a = np.asarray(coordinates)
x = a[:, 0]
y = a[:, 1]
fig, ax = plt.subplots()

j = 0

if showImages:
    squareLength = math.sqrt(len(dataList[0]))
    square = (squareLength, squareLength)
    for xpt, ypt in zip(x, y):
        img = np.array(dataList[j]).reshape(square)[::2, ::2]
        ab = AnnotationBbox(OffsetImage(img, cmap=cm.Greys_r), [xpt, ypt],
                            xybox=(65., 0),
                            xycoords='data',
                            boxcoords="offset points",
                            frameon=False,
                            arrowprops=dict(arrowstyle="->"))
        ax.add_artist(ab)
        j = j + 1
else:
    labels = ['image {0}'.format(i + 1) for i in range(len(x))]
    for label, xpt, ypt in zip(labels, x, y):
        plt.annotate(label,
                     xy=(xpt, ypt),
                     xytext=(-20, 20),
                     textcoords='offset points',
                     ha='right',
Beispiel #25
0
## ax.plot(x,y,
##         's',
##         fillstyle='none',
##         markeredgecolor=colors[1],
##         markeredgewidth=mew,
##         color=colors[1],
##         ms=ms,
##         label='Born-Mayer-IP FF (prior work)',
##         )
## x_min = min(x_min,np.min(x))
## x_max = max(x_max,np.max(x))
## y_min = min(y_min,np.min(y))
## y_max = max(y_max,np.max(y))
dimer = 'nh3.png'
arr_fig = read_png(dimer)
imagebox = OffsetImage(arr_fig, zoom=0.60)
xy = [0.1, 0.1]
xybox = [0.50,0.35]
ab = AnnotationBbox(imagebox, xy,
        xybox=xybox,
        xycoords='axes fraction',
        boxcoords="axes fraction",
        frameon=False,
                )
#arrowprops=dict(arrowstyle="->"))
mol = ax.add_artist(ab)

# Axes scaling and title settings
scale = 0.02
## x_min = np.amin(x)
## x_max = np.amax(x)
Beispiel #26
0
                )
                pylab.clabel(
                    contour,
                    fmt={contourLevel: pdb},
                    #fontsize='large'
                )
                ### End countour code ###
            pylab.xlabel('PC %s' % (pc_x + 1))
            pylab.ylabel('PC %s' % (pc_y + 1))
            if showMolAtAvgPos:
                #print ax
                #size = (150,150)
                #img = hsp90Helpers.getLigandAsImg(pdb, size=size)
                img = hsp90Helpers.getLigandAsImg(pdb)
                #pylab.figimage(np.array(img),np.mean(xs), np.mean(ys))
                imageBox = OffsetImage(np.array(img), zoom=1.0)
                xAvg = np.mean(xs)
                yAvg = np.mean(ys)

                distanceToSpots = ssd.cdist([[xAvg, yAvg]], xyCircPlaces)
                closestSpots = np.argsort(distanceToSpots)[0]
                spotFound = False
                for spotIndex in closestSpots:
                    if circPlacesTaken[spotIndex] == 0:
                        thisSpot = xyCircPlaces[spotIndex, :]
                        circPlacesTaken[spotIndex] = 1
                        spotFound = True
                        break
                if spotFound == False:
                    1 / 0
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, OffsetImage

img_filename = 'tsne_conv_ae_feat_nopool_layerwise_conv5.png'
fig = plt.gcf()
fig.clf()
fig.set_size_inches(40, 40)
fig.set_dpi(80)
ax = plt.subplot(111)
ax.set_xlim([np.min(vis_x) - 5, np.max(vis_x) + 5])
ax.set_ylim([np.min(vis_y) - 5, np.max(vis_y) + 5])

for idx in xrange(8780):
    bitmap = np.tile(bitmaps[idx], (1, 1, 3))

    imagebox = OffsetImage(bitmap, zoom=0.5)
    xy = [vis_x[idx], vis_y[idx]]
    #pdb.set_trace()
    #xy = vis_data[idx]

    ab = AnnotationBbox(
        imagebox,
        xy,
        #xybox=(10., -10.),
        xycoords='data',
        boxcoords="offset points",
        pad=0)
    ax.add_artist(ab)

    if idx % 100 == 0:
        print idx
def getImage(i, zoom=0.05):
    return OffsetImage(images[i][:, :, 0], zoom=zoom)
Beispiel #29
0
        ax.xaxis.pan(-1)
    elif event.key == 'up':
        ax.yaxis.pan(+1)
    elif event.key == 'down':
        ax.yaxis.pan(-1)
    draw()


fig = figure()
fig.canvas.mpl_connect('key_press_event', onpress)

ax = fig.gca()

ann = AnnotationBbox(
    OffsetImage(np.arange(256).reshape(16, 16) / 256.0,
                zoom=2,
                norm=None,
                origin=None),
    (0.5, 0.5),
    xybox=(30, 30),
    xycoords='data',
    boxcoords="offset points",
    frameon=True,
    pad=0.4,  # BboxPatch
    bboxprops=dict(boxstyle="round", fc="y"),
    fontsize=None,
    arrowprops=dict(arrowstyle="->"))

ax.add_artist(ann)

ann.draggable()
Beispiel #30
0
def test_plot_toolkit_units():
    swmmobject = PySWMM(*get_model_files(MODEL_TOOLKIT_UNITS_PATH))
    swmmobject.swmm_open()
    swmmobject.swmm_start()

    fig = plt.figure()
    ax = fig.add_subplot(2, 3, (1, 2))
    ax.set_ylabel('Flow Rate')
    line, = ax.plot([], [], label='C2')
    ax.grid()
    ax.legend()

    ax2 = fig.add_subplot(2, 3, (4, 5), sharex=ax)
    ax2.set_ylabel('Toolkit API\nInflow')
    line2, = ax2.plot([], [], label='J1')
    ax2.grid()

    xdata, ydata = [], []
    ydata2 = []

    ax3 = fig.add_subplot(2, 3, (3, 6))

    arr_lena = read_png(IMAGE_NODE_INFLOWS_PATH)
    imagebox = OffsetImage(arr_lena, zoom=0.67)
    ab = AnnotationBbox(
        imagebox,
        (0.5, 0.5),
        xybox=(0.5, 0.5),
        xycoords='data',
        boxcoords="offset points",
        pad=0.0,
    )
    ax3.add_artist(ab)
    ax3.axis('off')

    def data_gen(t=0):
        i = 0
        while (True):
            if i == 10:
                pass
                # j = swmmobject.setNodeInflow('J1', 1)
            time = swmmobject.swmm_stride(300)
            i += 1

            if i > 0 and time == 0.0:
                break
            if i > 0 and time > 0:
                yield time

    def run(t):
        xdata.append(t)
        new_y = swmmobject.getLinkResult('C2', 0)
        ydata.append(new_y)

        new_y2 = swmmobject.getNodeResult('J1', tka.NodeResults.newLatFlow)
        ydata2.append(new_y2)

        xmin, xmax = ax.get_xlim()
        ymin, ymax = ax.get_ylim()
        ymin2, ymax2 = ax2.get_ylim()

        # ax
        if new_y > ymax:
            ax.set_ylim(-0.1, 1.5 * ymax)

        if t >= xmax:
            ax.set_xlim(xmin, 1.5 * xmax)
            ax.figure.canvas.draw()

        line.set_data(xdata, ydata)

        # ax1
        if new_y2 > ymax2:
            ax2.set_ylim(-0.1, 1.2 * ymax2)
        line2.set_data(xdata, ydata2)

    ani = animation.FuncAnimation(fig,
                                  run,
                                  data_gen,
                                  blit=False,
                                  repeat=False,
                                  save_count=800,
                                  interval=10)

    show_fig = False
    if show_fig:
        plt.show()
    else:
        movie_path = os.path.join(DATA_PATH, "toolkit_units.mp4")
        print(movie_path, ani)
        # ani.save(movie_path, fps=20, dpi=170, bitrate=50000)

    swmmobject.swmm_end()
    swmmobject.swmm_report()
    swmmobject.swmm_close()

    plt.close()
    print("Check Passed")
Beispiel #31
0
def create_stack_chart(df: pd.DataFrame):
    """
    import numpy as np
    import pandas as pd
    from pandas import Series, DataFrame
    import matplotlib.pyplot as plt

    data1 = [23,85, 72, 43, 52]
    data2 = [42, 35, 21, 16, 9]
    plt.bar(range(len(data1)), data1)
    plt.bar(range(len(data2)), data2, bottom=data1)
    plt.show()
    """

    counts = get_ascent_counts(df)

    fig = plt.figure(figsize=(15, 10))
    ax = fig.add_subplot(1, 1, 1)
    major_ticks = np.arange(0, 26)
    ax.set_yticks(major_ticks)

    sum_ = copy.copy(counts['trad_onsights'])

    plt.barh(range(1, 25),
             counts['trad_onsights'],
             color='green',
             label='Trad onsight')
    plt.barh(range(1, 25),
             counts['sport_onsights'],
             left=sum_,
             color='#98ff98',
             label='Sport onsight')
    sum_ += counts['sport_onsights']
    plt.barh(range(1, 25),
             counts['trad_flashes'],
             left=sum_,
             color='#800020',
             label='Trad flash')
    sum_ += counts['trad_flashes']
    #plt.barh(range(1, 25), sport_flashes, left = trad_onsights + sport_onsights + trad_flashes, color='orange')
    plt.barh(range(1, 25),
             counts['trad_redpoints'],
             left=sum_,
             color='red',
             label='Trad redpoint')
    sum_ += counts['trad_redpoints']
    #plt.barh(range(1, 25), sport_redpoints, left = trad_onsights + sport_onsights + trad_flashes + sport_flashes + trad_redpoints, color='#FF00FF')
    plt.barh(range(1, 25),
             counts['pinkpoints'],
             left=sum_,
             color='pink',
             label='Pinkpoint (sport or trad)')
    sum_ += counts['pinkpoints']
    plt.barh(range(1, 25),
             counts['cleans'],
             left=sum_,
             color='xkcd:sky blue',
             label='Clean lead (yoyo, simulclimbing)')
    sum_ += counts['cleans']
    plt.barh(range(1, 25),
             counts['clean_seconds'],
             left=sum_,
             color='#FFA500',
             label='Clean second')
    sum_ += counts['clean_seconds']
    plt.barh(range(1, 25),
             counts['clean_topropes'],
             left=sum_,
             color='#FFFF00',
             label='Clean toprope')
    sum_ += counts['clean_topropes']
    plt.barh(range(1, 25),
             counts['battle_to_top'],
             left=sum_,
             color='gray',
             label='Battle to top (hangdog, second/toprope weighting rope)')

    _ = ax.legend(loc='center',
                  bbox_to_anchor=(0.5, -0.10),
                  shadow=False,
                  ncol=2)

    # Insert an image
    import matplotlib.image as mpimg
    from matplotlib.offsetbox import TextArea, DrawingArea, OffsetImage, AnnotationBbox
    from scipy import ndimage
    artists = []
    photo = mpimg.imread('animation/photos/20210704_160700.jpg')
    photo = ndimage.rotate(photo, -90)
    imagebox = OffsetImage(photo, zoom=0.1)
    ab = AnnotationBbox(imagebox, (8, 7))
    artists.append([ab])
    #photo = mpimg.imread('animation/photos/20210511_131111.jpg')
    #photo = ndimage.rotate(photo, -90)
    #imagebox = OffsetImage(photo, zoom=0.1)
    #ab = AnnotationBbox(imagebox, (8, 7))
    #artists.append([ab])
    #ax.add_artist(ab)
    #ax.imshow(photo)
    ax2 = fig.add_axes([0.3, 0.2, 0.7, 0.3])
    ims = []
    im = ax2.imshow(photo)
    ims.append([im])
    photo = mpimg.imread('animation/photos/20210511_131111.jpg')
    photo = ndimage.rotate(photo, -90)
    im = ax2.imshow(photo, animated=True)
    ims.append([im])
    print(ims)

    ani = animation.ArtistAnimation(fig, ims, interval=3050, blit=True)
    """
    def prep_anim(ab):
        def animate(frame_number):
            photo = mpimg.imread('animation/photos/20210511_131111.jpg')
            photo = ndimage.rotate(photo, -90)
            imagebox2 = OffsetImage(photo, zoom=0.1)
            ab.offsetbox = imagebox2
            #photo = mpimg.imread('animation/photos/20210511_131111.jpg')
            #imagebox.set_data(photo)
            #print(imagebox._data)
            #print('ok')
            #imagebox.draw()
            return ab
        return animate

    ani = animation.FuncAnimation(fig, prep_anim(ab), repeat=False, interval=2222, blit=True)
    """

    plt.show()
fig = plt.figure(figsize = (12,11))
ax = draw_court()
plt.scatter(shot_df.LOC_X, shot_df.LOC_Y)



''' 
DO NOT MESS WITH THESE PARAMETERS (they're standard among all plots)
'''

plt.xlim(-250, 250)
plt.ylim(422.5, -47.5)
plt.tick_params(labelbottom = False, labelleft = False)

ax.set_title('{0} {1} FGA \n{2} Regular Season'.format(args.player_first, args.player_last, year))
ax.text(-250,445, 'Data Source: stats.nba.com \nAuthor: Mohammad Saad (mohsaad.com)')

''' Draw Picture of Player '''
pic = urllib2.urlopen("http://stats.nba.com/media/players/230x185/{0}.png".format(str(player_id)),"{0}.png".format(str(player_id)))
player_pic = plt.imread(pic)
img = OffsetImage(player_pic, zoom = 0.6)
img.set_offset((900,110))
ax.add_artist(img)

# show plot
# plt.show()



# save the figure
fig.savefig("{0}_{1}_shot_chart_{2}.png".format(args.player_first, args.player_last, year))
Beispiel #33
0
def getImage(path):
    return OffsetImage(plt.imread(path), zoom=.33)
        if player['account_id'] == 37483323:
            match_details_list=[]
            match_details_list.append(player['hero_name'])
            match_details_list.append(player['kills'])
            match_details_list.append(player['deaths'])
            hero_pic_url = "http://cdn.dota2.com/apps/dota2/images/heroes/" + player['hero_name'].lower() + "_vert.jpg"
            hero_pic_url2 = player['hero_name'].lower() + "_vert.jpg"
            hero_pics.append(urllib.urlretrieve(hero_pic_url, hero_pic_url2))
    match_list.append(match_details_list)

dota_df = pd.DataFrame(match_list, columns=['hero_name', 'kills', 'deaths'])

#View the head of the DataFrame and all its columns
from IPython.display import display
with pd.option_context('display.max_columns', None):
        display(dota_df)

#Number of games played by hero
#hero_counts = dota_df['hero_name'].value_counts()
#hero_counts.plot(kind='barh')

kills_by_hero = dota_df.pivot_table(columns='hero_name', values='kills', aggfunc='sum')
sorted_kills_by_hero = kills_by_hero.order()
kills_graph = sorted_kills_by_hero.plot(kind='bar', width = 1)
plt.title("Kills by Hero - All Time")
plt.ylim(0, 100)

dota_pic = plt.imread(hero_pics[0][0])
img = OffsetImage(dota_pic, zoom=0.09)
img.set_offset((340,290))
kills_graph.add_artist(img)
Beispiel #35
0
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')

# Add a title
ax.set_title('Demarcus Cousins FGA \n2014-15 Reg. Season', 
             y=1.2, fontsize=18)

# Add Data Scource and Author
ax.text(-250,420,'Data Source: stats.nba.com'
        '\nAuthor: David Ko', fontsize=12)

# Add Harden;s image to the top right
# First create our OffSetImage by passing in our image
# and set the zoom level to make the image small enough 
# to fit on our plot
img = OffsetImage(dmc_pic, zoom=0.6)
# Pass in a tuple of x,y coordinates to set_offset
# to place the plot where you want, I just played around
# with the values until I found a spot where I wanted
# the image to be
img.set_offset((625,621))
# add the image
ax.add_artist(img)

plt.show()



# create our jointplot

cmap=plt.cm.gist_heat_r
def visualize():
    fig = plt.figure()

    ax = plt.axes()

    points_with_annotation = []

    themap = Basemap(projection='gall',
                llcrnrlon = -180,
                llcrnrlat = -90,
                urcrnrlon = 180,
                urcrnrlat = 90,
                resolution = 'l',
                area_thresh = 100000.0,
                )

    themap.drawcoastlines()
    themap.drawcountries()
    themap.fillcontinents(color = 'gainsboro')
    themap.drawmapboundary(fill_color='steelblue')

    #site 1
    x1, y1 = themap(0,44)
    point, = themap.plot(x1, y1, 'o', color='Red',markersize=10)
    fn = get_sample_data("/Users/rogpaxton/Galvanize/SiteMetrics/plot44.0.png", asfileobj=False)
    arr_lena = read_png(fn)
    imagebox = OffsetImage(arr_lena, zoom=0.5)
    xy1 = (0, 44)

    annotation = AnnotationBbox(imagebox, xy1,
                        xybox=(50, 150),
                        xycoords='data',
                        boxcoords="offset points",
                        pad=0.5,
                        arrowprops=dict(arrowstyle="->",
                                        #connectionstyle="angle,angleA=0,angleB=90,rad=3")
                        ))

    annotation.set_visible(False)

    points_with_annotation.append([point, annotation])

    x2, y2 = themap(90,44)
    themap.plot(x2, y2,
            'o',                    # marker shape
            color='Red',         # marker colour
            markersize=6            # marker size
            )

    #site 2
    x2, y2 = themap(90,44)
    point, = themap.plot(x2, y2, 'o', color='Red',markersize=10)
    fn = get_sample_data("/Users/rogpaxton/Galvanize/SiteMetrics/plot45.0.png", asfileobj=False)
    arr_lena = read_png(fn)
    imagebox = OffsetImage(arr_lena, zoom=0.5)
    xy2 = (90, 44)

    annotation = AnnotationBbox(imagebox, xy2,
                        xybox=(50, 150),
                        xycoords='data',
                        boxcoords="offset points",
                        pad=0.5,
                        #arrowprops=dict(arrowstyle="->",
                                        #connectionstyle="angle,angleA=0,angleB=90,rad=3")
                        )

    annotation.set_visible(False)

    points_with_annotation.append([point, annotation])

    #site 3
    x3, y3 = themap(120,-34)
    point, = themap.plot(x3, y3, 'o', color='Red',markersize=10)
    fn = get_sample_data("/Users/rogpaxton/Galvanize/SiteMetrics/plot46.0.png", asfileobj=False)
    arr_lena = read_png(fn)
    imagebox = OffsetImage(arr_lena, zoom=0.5)
    #image = mpimg.imread("plot44.0.png")
    xy3 = (120, -34)

    annotation = AnnotationBbox(imagebox, xy3,
                        xybox=(50, 150),
                        xycoords='data',
                        boxcoords="offset points",
                        pad=0.5,
                        arrowprops=dict(arrowstyle="->",
                                        connectionstyle="angle,angleA=0,angleB=90,rad=3")
                        )

    annotation.set_visible(False)

    points_with_annotation.append([point, annotation])

    #Mouseover
    
    def on_move(event):
        visibility_changed = False
        for point, annotation in points_with_annotation:
            ax.add_artist(annotation)
            should_be_visible = (point.contains(event)[0] == True)

            if should_be_visible != annotation.get_visible():
                visibility_changed = True
                annotation.set_visible(should_be_visible)

        if visibility_changed:

            plt.draw()


    on_move_id = fig.canvas.mpl_connect('motion_notify_event', on_move)


    plt.show()
Beispiel #37
0
def visualize_clusters(x, y, imgs, colors=None):
    """create an interactive plot visualizing the clusters
       hovering over a point shows the corresponding face crop"""
    # create figure and plot scatter
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.tick_params(axis='x',
                   which='both',
                   bottom=False,
                   top=False,
                   labelbottom=False)
    ax.tick_params(axis='y',
                   which='both',
                   left=False,
                   right=False,
                   labelleft=False)
    if colors:
        line, = ax.plot(x, y, ls="")
        ax.scatter(x, y, c=colors)
    else:
        line, = ax.plot(x, y, ls="", marker="o")

    # create the annotations box
    im = OffsetImage(imgs[0], zoom=1)
    xybox = (50., 50.)
    ab = AnnotationBbox(im, (0, 0),
                        xybox=xybox,
                        xycoords='data',
                        boxcoords="offset points",
                        pad=0.3,
                        arrowprops=dict(arrowstyle="->"))
    # add it to the axes and make it invisible
    ax.add_artist(ab)
    ab.set_visible(False)

    def hover(event):
        # if the mouse is over the scatter points
        if line.contains(event)[0]:
            # find out the index within the array from the event
            ind, = line.contains(event)[1]["ind"]
            # get the figure size
            w, h = fig.get_size_inches() * fig.dpi
            ws = (event.x > w / 2.) * -1 + (event.x <= w / 2.)
            hs = (event.y > h / 2.) * -1 + (event.y <= h / 2.)
            # if event occurs in the top or right quadrant of the figure,
            # change the annotation box position relative to mouse.
            ab.xybox = (xybox[0] * ws, xybox[1] * hs)
            # make annotation box visible
            ab.set_visible(True)
            # place it at the position of the hovered scatter point
            ab.xy = (x[ind], y[ind])
            # set the image corresponding to that point
            #im.set_data(imgs[ind][:,:,::-1])
            im.set_data(imgs[ind])
        else:
            #if the mouse is not over a scatter point
            ab.set_visible(False)
        fig.canvas.draw_idle()

    # add callback for mouse moves
    fig.canvas.mpl_connect('motion_notify_event', hover)
    plt.show()
imgs.shape

imgs_vector = imgs.reshape(imgs.shape[0], -1)

embedding = umap.UMAP(n_neighbors=100, min_dist=0.0).fit_transform(imgs_vector)

# +
#https://stackoverflow.com/questions/42867400/python-show-image-upon-hovering-over-a-point

x = embedding[:, 0]
y = embedding[:, 1]

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot(x, y, ls="", marker="o")
im = OffsetImage(imgs[0, :, :, :], zoom=.5)

xybox = (50., 50.)
ab = AnnotationBbox(im, (0, 0),
                    xybox=xybox,
                    xycoords='data',
                    boxcoords="offset points",
                    pad=0.3,
                    arrowprops=dict(arrowstyle="->"))
# add it to the axes and make it invisible
ax.add_artist(ab)
ab.set_visible(False)


def hover(event):
    # if the mouse is over the scatter points
Beispiel #39
0
pd.set_option('display.width', 200)

response = requests.get(shot_chart_url)
headers = response.json()['resultSets'][0]['headers']
shots = response.json()['resultSets'][0]['rowSet']
 
shot_df = pd.DataFrame(shots, columns=headers)

sns.set_style("white")
sns.set_color_codes()
# sns.despine(left=True)

pic = urllib.urlretrieve("http://stats.nba.com/media/players/230x185/101108.png", "101108.png")
paul_pic = plt.imread(pic[0])

img = OffsetImage(paul_pic, zoom=0.6)
img.set_offset((400,350))
cmap=plt.cm.gist_heat_r

# plt.axis('off')
# plt.figure(figsize=(12,11))
# plt.figure(figsize=(6,5.5))
# cp3 = plt.hexbin(shot_df.LOC_X, shot_df.LOC_Y, gridsize=[20,7])

joint_shot_chart = sns.jointplot(shot_df.LOC_X, shot_df.LOC_Y, size=7.5, stat_func=None,
                                 kind='hex', space=0, gridsize=[20,6], color=cmap(.2), cmap=cmap)

ax = joint_shot_chart.ax_joint

ax.set_xlim(-250,250)
ax.set_ylim(422.5, -47.5)
Beispiel #40
0
def make_annotation_bbox(image, loc, offset_image_kwargs={"cmap": "Greys"}):
    imagebox = OffsetImage(image, zoom=2.0, **offset_image_kwargs)
    ab = AnnotationBbox(imagebox, loc)
    return ab