示例#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()
示例#2
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()
示例#3
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()
示例#4
0
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)
示例#5
0
    for element in court_elements:
        ax.add_patch(element)

    return ax


#plt.figure(figsize=(12,11))
#draw_court(outer_lines=True)
#plt.xlim(-300,300)
#plt.ylim(-100,500)
#plt.show()

plt.figure(figsize=(12, 11))
plt.scatter(df.LOC_X, df.LOC_Y, facecolors="none", edgecolors='g')
draw_court(outer_lines=True)
# Descending values along the axis from left to right
plt.xlim(300, -300)
plt.ylim(-50, 500)

plt.title("Giannis Antetokounmpo Made Baskets Shot Chart")
plt.text(0, 300, "Data: nba.stats.com\nGraph made by Ankith Kodali")

pic = urllib.request.urlretrieve(
    "http://stats.nba.com/media/players/230x185/203507.png", "203507.png")

giannis_pic = plt.imread(pic[0])
img = OffsetImage(giannis_pic, zoom=0.6)

img.set_offset((625, 621))
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))
示例#7
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()
示例#8
0
# Draw court
ax = create_court(ax, 'black')

# Plot hexbin of shots
ax.hexbin(player_data['LOC_X'],
          player_data['LOC_Y'] + 60,
          gridsize=(30, 30),
          extent=(-300, 300, 0, 940),
          bins='log',
          cmap='Blues')

#Add Player Picture

player_imagebox = OffsetImage(player_profile_pic, zoom=0.32)
player_imagebox.set_offset((0, 0))
xy = [0, 0]
ab_player_imagebox = AnnotationBbox(player_imagebox,
                                    xy,
                                    xybox=(-102, -237),
                                    boxcoords='offset points',
                                    frameon=False)
ax.add_artist(ab_player_imagebox)

# Put the logo behind
#team_logo_img = OffsetImage(team_logo, zoom=1)
#team_logo_img.set_offset((180,250))
#ax.add_artist(team_logo_img)

# Put the logo over
team_imagebox = OffsetImage(team_logo, zoom=0.4)
示例#9
0
             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
joint_shot_chart = sns.jointplot(shot_df.LOC_X, shot_df.LOC_Y, stat_func=None,
                                 kind='hex', space=0, color=cmap(.2), cmap=cmap)

joint_shot_chart.fig.set_size_inches(12,11)
示例#10
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()
示例#11
0
def AnotacionesJugador(p_id, season, gametype):
    def draw_court(ax=None, color='black', lw=2, outer_lines=False):
        # If an axes object isn't provided to plot onto, just get current one
        if ax is None:
            ax = plt.gca()

        # Create the various parts of an NBA basketball court

        # Create the basketball hoop
        # Diameter of a hoop is 18" so it has a radius of 9", which is a value
        # 7.5 in our coordinate system
        hoop = Circle((0, 0),
                      radius=7.5,
                      linewidth=lw,
                      color=color,
                      fill=False)

        # Create backboard
        backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color)

        # The paint
        # Create the outer box 0f the paint, width=16ft, height=19ft
        outer_box = Rectangle((-80, -47.5),
                              160,
                              190,
                              linewidth=lw,
                              color=color,
                              fill=False)
        # Create the inner box of the paint, widt=12ft, height=19ft
        inner_box = Rectangle((-60, -47.5),
                              120,
                              190,
                              linewidth=lw,
                              color=color,
                              fill=False)

        # Create free throw top arc
        top_free_throw = Arc((0, 142.5),
                             120,
                             120,
                             theta1=0,
                             theta2=180,
                             linewidth=lw,
                             color=color,
                             fill=False)
        # Create free throw bottom arc
        bottom_free_throw = Arc((0, 142.5),
                                120,
                                120,
                                theta1=180,
                                theta2=0,
                                linewidth=lw,
                                color=color,
                                linestyle='dashed')
        # Restricted Zone, it is an arc with 4ft radius from center of the hoop
        restricted = Arc((0, 0),
                         80,
                         80,
                         theta1=0,
                         theta2=180,
                         linewidth=lw,
                         color=color)

        # Three point line
        # Create the side 3pt lines, they are 14ft long before they begin to arc
        corner_three_a = Rectangle((-220, -47.5),
                                   0,
                                   140,
                                   linewidth=lw,
                                   color=color)
        corner_three_b = Rectangle((220, -47.5),
                                   0,
                                   140,
                                   linewidth=lw,
                                   color=color)
        # 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop
        # I just played around with the theta values until they lined up with the
        # threes
        three_arc = Arc((0, 0),
                        475,
                        475,
                        theta1=22,
                        theta2=158,
                        linewidth=lw,
                        color=color)

        # Center Court
        center_outer_arc = Arc((0, 422.5),
                               120,
                               120,
                               theta1=180,
                               theta2=0,
                               linewidth=lw,
                               color=color)
        center_inner_arc = Arc((0, 422.5),
                               40,
                               40,
                               theta1=180,
                               theta2=0,
                               linewidth=lw,
                               color=color)

        # List of the court elements to be plotted onto the axes
        court_elements = [
            hoop, backboard, outer_box, inner_box, top_free_throw,
            bottom_free_throw, restricted, corner_three_a, corner_three_b,
            three_arc, center_outer_arc, center_inner_arc
        ]

        if outer_lines:
            # Draw the half court line, baseline and side out bound lines
            outer_lines = Rectangle((-250, -47.5),
                                    500,
                                    470,
                                    linewidth=lw,
                                    color=color,
                                    fill=False)
            court_elements.append(outer_lines)

        # Add the court elements onto the axes
        for element in court_elements:
            ax.add_patch(element)

        return ax

    response = shotchartdetail.ShotChartDetail(team_id=0,
                                               player_id=p_id,
                                               season_nullable=season,
                                               season_type_all_star=gametype)

    content = json.loads(response.get_json())

    # transform contents into dataframe
    results = content['resultSets'][0]
    headers = results['headers']
    rows = results['rowSet']
    shot_df = pd.DataFrame(rows)
    shot_df.columns = headers

    ssl._create_default_https_context = ssl._create_unverified_context
    # we pass in the link to the image as the 1st argument
    pic = urllib.request.urlretrieve(
        f"http://stats.nba.com/media/players/230x185/{p_id}.png",
        f"{p_id}.png")

    # urlretrieve returns a tuple with our image as the first
    # element and imread reads in the image as a
    # mutlidimensional numpy array so matplotlib can plot it
    harden_pic = plt.imread(pic[0])

    # 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.gist_heat_r

    # n_levels sets the number of contour lines for the main kde plot
    joint_shot_chart = sns.jointplot(shot_df.LOC_X,
                                     shot_df.LOC_Y,
                                     stat_func=None,
                                     kind='kde',
                                     space=0,
                                     color=cmap(0.1),
                                     cmap=cmap,
                                     n_levels=50)

    joint_shot_chart.fig.set_size_inches(12, 11)

    # A joint plot has 3 Axes, the first one called ax_joint,
    # It's the one we want to draw our court onto and adjust some other settings
    ax = joint_shot_chart.ax_joint
    draw_court(ax, color="gray", lw=1)

    # 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 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(harden_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()
示例#12
0
# draw court onto ax_joint axis
ax = shot_chart.ax_joint
court(ax)

# adjust orientation of court/halcourt --> hoop at the top of the plot
ax.set_xlim(-250, 250)
ax.set_ylim(422.5, -47.5)

# remove tick marks and axis lavels
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')

# add title
ax.set_title('Kawhi Leonard FGM \n2020-21 Reg. Season', y=1.2, fontsize=18)

# add data source and author
ax.text(-250,
        465, 'Data source: stats.nba.com'
        '\nAuthor: Aram Martin',
        fontsize=12)

# add image to the top right of our graph
img = OffsetImage(kawhi_pic, zoom=0.2)
img.set_offset((625, 650))

# add image
ax.add_artist(img)

plt.show()
示例#13
0
made = shot_df[shot_df['SHOT_MADE_FLAG'] == 1]
miss = shot_df[shot_df['SHOT_MADE_FLAG'] == 0]
plt.scatter(miss.LOC_X, miss.LOC_Y, color='r', marker='.', alpha=0.3)
plt.scatter(made.LOC_X, made.LOC_Y, color='b', marker='.', alpha=0.3)

print('绘制球场...')
draw_court()
# 调整 x 轴使其适应半场
plt.xlim(-250, 250)
# y 轴值从下到上依次递减
# 便于将球筐至于图的顶部
plt.ylim(422.5, -47.5)
# 消除坐标轴刻度
plt.tick_params(labelbottom=False, labelleft=False)

print('绘制头像...')
#将球员图片放置于右上角,并设置缩小等级以配合整个图片
img = OffsetImage(head_pic, zoom=0.6)
# (x, y) 控制将球员放在你想要放的位置
img.set_offset((1600, 1800))
# 添加球员图片
fig.gca().add_artist(img)
# 添加标题
name = shot_df.iloc[1]['PLAYER_NAME']
fig.suptitle(name + ', 2018-19', y=1.03, fontsize=18)
# 消除刻度
plt.tick_params(labelbottom=False, labelleft=False)
#保存图片,添加自己的路径
plt.savefig(name + '.png', bbox_inches='tight', pad_inches=0.5, dpi=fig.dpi)
plt.show()
示例#14
0
sns.set_color_codes()
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))
        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)