Exemplo n.º 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()
Exemplo n.º 2
0
def make_histogram(df, player_name, year, season_type, chart_type):
    plt.figure()
    title = player_name + ' ' + dg.get_year_string(year) + ' ' + season_type
    plt.title(title)
    plt.xlabel('Distance (Feet)')
    df['SHOT_DISTANCE'].plot.hist(alpha=0.5)
    file_path = '../charts/' + chart_type + '/hist/' + player_name + '_' + str(year) + '_' + season_type + '.png'
    dg.create_directories_and_check_for_file(file_path)
    plt.savefig(file_path)
    plt.close()
Exemplo n.º 3
0
def get_player_picture(player_id, player_name):
    file_path = '../player_pictures/' + player_name + '.png'
    if not dg.create_directories_and_check_for_file(file_path):
        pic = urllib.urlretrieve("http://stats.nba.com/media/players/230x185/" + str(player_id) + ".png",
                                 str(player_id) + ".png")
        player_pic = plt.imread(pic[0])
        plt.imsave(file_path, player_pic)
    else:
        player_pic = plt.imread(file_path)
    return player_pic
Exemplo n.º 4
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()
Exemplo n.º 5
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()
def merge_pbp_and_shot_data(year):
    file_path = "../data/merged_shot_pbp/" + str(year) + ".csv"
    if not data.create_directories_and_check_for_file(file_path):
        game_ids = get_season_game_ids(year)
        full_year_merged_df = pd.DataFrame()

        shot_df = data.get_shot_data(overwrite=False, season_year=year)
        shot_df = shot_df[
            [
                "ACTION_TYPE",
                "EVENT_TYPE",
                "GAME_EVENT_ID",
                "GAME_ID",
                "LOC_X",
                "LOC_Y",
                "SHOT_DISTANCE",
                "SHOT_MADE_FLAG",
                "SHOT_TYPE",
                "SHOT_ZONE_AREA",
                "SHOT_ZONE_BASIC",
                "SHOT_ZONE_RANGE",
            ]
        ]

        for i, game_id in enumerate(game_ids):
            print(i, game_id)
            pbp_df = data.get_pbp_data(game_id, data.get_year_string(year), data.SeasonTypes.REG, overwrite=False)
            try:
                pbp_df = pbp_df[
                    [
                        "GAME_ID",
                        "EVENTNUM",
                        "PERIOD",
                        "PCTIMESTRING",
                        "HOMEDESCRIPTION",
                        "NEUTRALDESCRIPTION",
                        "VISITORDESCRIPTION",
                        "PLAYER1_ID",
                        "PLAYER1_NAME",
                        "PLAYER1_TEAM_ID",
                        "PLAYER2_ID",
                        "PLAYER2_NAME",
                        "PLAYER2_TEAM_ID",
                        "PLAYER3_ID",
                        "PLAYER3_NAME",
                        "PLAYER3_TEAM_ID",
                    ]
                ]

                merge_df = pd.merge(
                    pbp_df, shot_df, left_on=["GAME_ID", "EVENTNUM"], right_on=["GAME_ID", "GAME_EVENT_ID"], how="inner"
                )
            except KeyError:
                print("KEY ERROR")

        full_year_merged_df = full_year_merged_df.append(merge_df)
        full_year_merged_df.to_csv("../data/merged_shot_pbp/" + str(year) + ".csv")
        return full_year_merged_df

    else:
        return pd.read_csv(file_path)