首先,我們需要獲得每個(gè)球員的投籃數(shù)據(jù)。利用 Savvas Tjortjoglou 貼出的代碼,筆者從 NBA.com 網(wǎng)站 API 上獲取了數(shù)據(jù)。在此不會(huì)貼出這個(gè)函數(shù)的結(jié)果。如果你感興趣,推薦你去看看 Savvas Tjortjoglou 的博客。

創(chuàng)新互聯(lián)自2013年創(chuàng)立以來(lái),是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元舒城做網(wǎng)站,已為上家服務(wù),為舒城各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
def aqcuire_shootingData(PlayerID,Season):
import requests
shot_chart_url = ';CFPARAMS='+Season+'ContextFilter='\
'ContextMeasure=FGADateFrom=DateTo=GameID=GameSegment=LastNGames=0LeagueID='\
'00Location=MeasureType=BaseMonth=0OpponentTeamID=0Outcome=PaceAdjust='\
'NPerMode=PerGamePeriod=0PlayerID='+PlayerID+'PlusMinus=NPosition=Rank='\
'NRookieYear=Season='+Season+'SeasonSegment=SeasonType=Regular+SeasonTeamID='\
'0VsConference=VsDivision=mode=AdvancedshowDetails=0showShots=1showZones=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)
return shot_df
接下來(lái),我們需要繪制一個(gè)包含得分圖的籃球場(chǎng)圖。該籃球場(chǎng)圖例必須使用與NBA.com API 相同的坐標(biāo)系統(tǒng)。例如,3分位置的投籃距籃筐必須為 X 單位,上籃距離籃筐則是 Y 單位。同樣,筆者再次使用了 Savvas Tjortjoglou 的代碼(哈哈,否則的話,搞明白 NBA.com 網(wǎng)站的坐標(biāo)系統(tǒng)肯定會(huì)耗費(fèi)不少的時(shí)間)。
def draw_court(ax=None, color='black', lw=2, outer_lines=False):
from matplotlib.patches import Circle, Rectangle, Arc
if ax is None:
ax = plt.gca()
hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False)
backboard = Rectangle((-30, -7.5), 60, -1, linewidth=lw, color=color)
outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color,
fill=False)
inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color,
fill=False)
top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180,
linewidth=lw, color=color, fill=False)
bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0,
linewidth=lw, color=color, linestyle='dashed')
restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw,
color=color)
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)
three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw,
color=color)
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)
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:
outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw,
color=color, fill=False)
court_elements.append(outer_lines)
for element in court_elements:
ax.add_patch(element)
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_xticks([])
ax.set_yticks([])
return ax
我想創(chuàng)造一個(gè)不同位置的投籃百分比數(shù)組,因此決定利用 matplot 的 Hexbin 函數(shù) 將投籃位置均勻地分組到六邊形中。該函數(shù)會(huì)對(duì)每個(gè)六邊形中每一個(gè)位置的投籃次數(shù)進(jìn)行計(jì)數(shù)。
六邊形是均勻的分布在 XY 網(wǎng)格中。「gridsize」變量控制六邊形的數(shù)目。「extent」變量控制第一個(gè)和最后一個(gè)六邊形的繪制位置(一般來(lái)說(shuō)第一個(gè)六邊形的位置基于第一個(gè)投籃的位置)。
計(jì)算命中率則需要對(duì)每個(gè)六邊形中投籃的次數(shù)和投籃得分次數(shù)進(jìn)行計(jì)數(shù),因此筆者對(duì)同一位置的投籃和得分?jǐn)?shù)分別運(yùn)行 hexbin 函數(shù)。然后,只需用每個(gè)位置的進(jìn)球數(shù)除以投籃數(shù)。
def find_shootingPcts(shot_df, gridNum):
x = shot_df.LOC_X[shot_df['LOC_Y']425.1] #i want to make sure to only include shots I can draw
y = shot_df.LOC_Y[shot_df['LOC_Y']425.1]
x_made = shot_df.LOC_X[(shot_df['SHOT_MADE_FLAG']==1) (shot_df['LOC_Y']425.1)]
y_made = shot_df.LOC_Y[(shot_df['SHOT_MADE_FLAG']==1) (shot_df['LOC_Y']425.1)]
#compute number of shots made and taken from each hexbin location
hb_shot = plt.hexbin(x, y, gridsize=gridNum, extent=(-250,250,425,-50));
plt.close() #don't want to show this figure!
hb_made = plt.hexbin(x_made, y_made, gridsize=gridNum, extent=(-250,250,425,-50),cmap=plt.cm.Reds);
plt.close()
#compute shooting percentage
ShootingPctLocs = hb_made.get_array() / hb_shot.get_array()
ShootingPctLocs[np.isnan(ShootingPctLocs)] = 0 #makes 0/0s=0
return (ShootingPctLocs, hb_shot)
筆者非常喜歡 Savvas Tjortjoglou 在他的得分圖中加入了球員頭像的做法,因此也順道用了他的這部分代碼。球員照片會(huì)出現(xiàn)在得分圖的右下角。
def acquire_playerPic(PlayerID, zoom, offset=(250,400)):
from matplotlib import offsetbox as osb
import urllib
pic = urllib.urlretrieve(""+PlayerID+".png",PlayerID+".png")
player_pic = plt.imread(pic[0])
img = osb.OffsetImage(player_pic, zoom)
#img.set_offset(offset)
img = osb.AnnotationBbox(img, offset,xycoords='data',pad=0.0, box_alignment=(1,0), frameon=False)
return img
筆者想用連續(xù)的顏色圖來(lái)描述投籃進(jìn)球百分比,紅圈越多代表著更高的進(jìn)球百分比。雖然「紅」顏色圖示效果不錯(cuò),但是它會(huì)將0%的投籃進(jìn)球百分比顯示為白色,而這樣顯示就會(huì)不明顯,所以筆者用淡粉紅色代表0%的命中率,因此對(duì)紅顏色圖做了下面的修改。
#cmap = plt.cm.Reds
#cdict = cmap._segmentdata
cdict = {
'blue': [(0.0, 0.6313725709915161, 0.6313725709915161), (0.25, 0.4470588266849518, 0.4470588266849518), (0.5, 0.29019609093666077, 0.29019609093666077), (0.75, 0.11372549086809158, 0.11372549086809158), (1.0, 0.05098039284348488, 0.05098039284348488)],
'green': [(0.0, 0.7333333492279053, 0.7333333492279053), (0.25, 0.572549045085907, 0.572549045085907), (0.5, 0.4156862795352936, 0.4156862795352936), (0.75, 0.0941176488995552, 0.0941176488995552), (1.0, 0.0, 0.0)],
'red': [(0.0, 0.9882352948188782, 0.9882352948188782), (0.25, 0.9882352948188782, 0.9882352948188782), (0.5, 0.9843137264251709, 0.9843137264251709), (0.75, 0.7960784435272217, 0.7960784435272217), (1.0, 0.40392157435417175, 0.40392157435417175)]
}
mymap = mpl.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)
好了,現(xiàn)在需要做的就是將它們合并到一塊兒。下面所示的較大函數(shù)會(huì)利用上文描述的函數(shù)來(lái)創(chuàng)建一個(gè)描述投籃命中率的得分圖,百分比由紅圈表示(紅色越深 = 更高的命中率),投籃次數(shù)則由圓圈的大小決定(圓圈越大 = 投籃次數(shù)越多)。需要注意的是,圓圈在交疊之前都能增大。一旦圓圈開始交疊,就無(wú)法繼續(xù)增大。
在這個(gè)函數(shù)中,計(jì)算了每個(gè)位置的投籃進(jìn)球百分比和投籃次數(shù)。然后畫出在該位置投籃的次數(shù)(圓圈大小)和進(jìn)球百分比(圓圈顏色深淺)。
def shooting_plot(shot_df, plot_size=(12,8),gridNum=30):
from matplotlib.patches import Circle
x = shot_df.LOC_X[shot_df['LOC_Y']425.1]
y = shot_df.LOC_Y[shot_df['LOC_Y']425.1]
#compute shooting percentage and # of shots
(ShootingPctLocs, shotNumber) = find_shootingPcts(shot_df, gridNum)
#draw figure and court
fig = plt.figure(figsize=plot_size)#(12,7)
cmap = mymap #my modified colormap
ax = plt.axes([0.1, 0.1, 0.8, 0.8]) #where to place the plot within the figure
draw_court(outer_lines=False)
plt.xlim(-250,250)
plt.ylim(400, -25)
#draw player image
zoom = np.float(plot_size[0])/(12.0*2) #how much to zoom the player's pic. I have this hackily dependent on figure size
img = acquire_playerPic(PlayerID, zoom)
ax.add_artist(img)
#draw circles
for i, shots in enumerate(ShootingPctLocs):
restricted = Circle(shotNumber.get_offsets()[i], radius=shotNumber.get_array()[i],
color=cmap(shots),alpha=0.8, fill=True)
if restricted.radius 240/gridNum: restricted.radius=240/gridNum
ax.add_patch(restricted)
#draw color bar
ax2 = fig.add_axes([0.92, 0.1, 0.02, 0.8])
cb = mpl.colorbar.ColorbarBase(ax2,cmap=cmap, orientation='vertical')
cb.set_label('Shooting %')
cb.set_ticks([0.0, 0.25, 0.5, 0.75, 1.0])
cb.set_ticklabels(['0%','25%', '50%','75%', '100%'])
plt.show()
return ax
好了,大功告成!因?yàn)楣P者是森林狼隊(duì)的粉絲,在下面用幾分鐘跑出了森林狼隊(duì)前六甲的得分圖。
PlayerID = '203952' #andrew wiggins
shot_df = aqcuire_shootingData(PlayerID,'2015-16')
ax = shooting_plot(shot_df, plot_size=(12,8));
在 python 中使用 matplotlib 繪制散點(diǎn)圖時(shí),可以使用 xtick.set_rotation() 函數(shù)來(lái)設(shè)置 x 軸刻度標(biāo)簽的旋轉(zhuǎn)角度。例如,要將 x 軸刻度標(biāo)簽傾斜 45 度,可以使用以下代碼:
Copy code
import matplotlib.pyplot as plt
# 繪制散點(diǎn)圖
plt.scatter(x, y)
# 獲取 x 軸的刻度對(duì)象
xticks = plt.gca().get_xticks()
# 設(shè)置 x 軸刻度標(biāo)簽的旋轉(zhuǎn)角度
plt.gca().set_xticklabels(xticks, rotation=45)
# 顯示圖形
plt.show()
在這段代碼中,我們使用 plt.scatter() 函數(shù)繪制散點(diǎn)圖,然后使用 plt.gca().get_xticks() 函數(shù)獲取 x 軸的刻度對(duì)象。接著,我們使用 plt.gca().set_xticklabels() 函數(shù)設(shè)置 x 軸刻度標(biāo)簽的旋轉(zhuǎn)角度,最后使用 plt.show() 函數(shù)顯示圖形。
注意:在調(diào)用 plt.scatter() 函數(shù)之前,需要先設(shè)置 x 和 y 軸的數(shù)據(jù)。
1,xlable,ylable設(shè)置x,y軸的標(biāo)題文字。
2,title設(shè)置標(biāo)題。
3,xlim,ylim設(shè)置x,y軸顯示范圍。
plt.show()顯示繪圖窗口,通常情況下,show()會(huì)阻礙程序運(yùn)行,帶-wthread等參數(shù)的環(huán)境下,窗口不會(huì)關(guān)閉。
plt.saveFig()保存圖像。
面向?qū)ο罄L圖
1,當(dāng)前圖表和子圖可以用gcf(),gca()獲得。
subplot()繪制包含多個(gè)圖表的子圖。
configure subplots,可調(diào)節(jié)子圖與圖表邊框距離。
可以通過修改配置文件更改對(duì)象屬性。
圖標(biāo)顯示中文
1,在程序中直接指定字體。
2, 在程序開始修改配置字典reParams.
3,修改配置文件。
Artist對(duì)象
1,圖標(biāo)的繪制領(lǐng)域。
2,如何在FigureCanvas對(duì)象上繪圖。
3,如何使用Renderer在FigureCanvas對(duì)象上繪圖。
FigureCanvas和Render處理底層圖像操作,Artist處理高層結(jié)構(gòu)。
分為簡(jiǎn)單對(duì)象和容器對(duì)象,簡(jiǎn)單的Aritist是標(biāo)準(zhǔn)的繪圖元件,例如Line 2D,Rectangle,Text,AxesImage等,而容器類型包含許多簡(jiǎn)單的的 Aritist對(duì)象,使他們構(gòu)成一個(gè)整體,例如Axis,Axes,Figure等。
直接創(chuàng)建Artist對(duì)象進(jìn)項(xiàng)繪圖操作步奏:
1,創(chuàng)建Figure對(duì)象(通過figure()函數(shù),會(huì)進(jìn)行許多初始化操作,不建議直接創(chuàng)建。)
2,為Figure對(duì)象創(chuàng)建一個(gè)或多個(gè)Axes對(duì)象。
3,調(diào)用Axes對(duì)象的方法創(chuàng)建各類簡(jiǎn)單的Artist對(duì)象。
Figure容器
如何找到指定的Artist對(duì)象。
1,可調(diào)用add_subplot()和add_axes()方法向圖表添加子圖。
2,可使用for循環(huán)添加?xùn)鸥瘛?/p>
3,可通過transform修改坐標(biāo)原點(diǎn)。
Axes容器
1,patch修改背景。
2,包含坐標(biāo)軸,坐標(biāo)網(wǎng)格,刻度標(biāo)簽,坐標(biāo)軸標(biāo)題等內(nèi)容。
3,get_ticklabels(),,get-ticklines獲得刻度標(biāo)簽和刻度線。
1,可對(duì)曲線進(jìn)行插值。
2,fill_between()繪制交點(diǎn)。
3,坐標(biāo)變換。
4,繪制陰影。
5,添加注釋。
1,繪制直方圖的函數(shù)是
2,箱線圖(Boxplot)也稱箱須圖(Box-whisker Plot),是利用數(shù)據(jù)中的五個(gè)統(tǒng)計(jì)量:最小值、第一四分位
數(shù)、中位數(shù)、第三四分位數(shù)與最大值來(lái)描述數(shù)據(jù)的一種方法,它可以粗略地看出數(shù)據(jù)是否具有對(duì)稱性以及分
布的分散程度等信息,特別可以用于對(duì)幾個(gè)樣本的比較。
3,餅圖就是把一個(gè)圓盤按所需表達(dá)變量的觀察數(shù)劃分為若干份,每一份的角度(即面積)等價(jià)于每個(gè)觀察
值的大小。
4,散點(diǎn)圖
5,QQ圖
低層繪圖函數(shù)
類似于barplot(),dotchart()和plot()這樣的函數(shù)采用低層的繪圖函數(shù)來(lái)畫線和點(diǎn),來(lái)表達(dá)它們?cè)陧?yè)面上放置的位置以及其他各種特征。
在這一節(jié)中,我們會(huì)描述一些低層的繪圖函數(shù),用戶也可以調(diào)用這些函數(shù)用于繪圖。首先我們先講一下R怎么描述一個(gè)頁(yè)面;然后我們講怎么在頁(yè)面上添加點(diǎn),線和文字;最后講一下怎么修改一些基本的圖形。
繪圖區(qū)域與邊界
R在繪圖時(shí),將顯示區(qū)域劃分為幾個(gè)部分。繪制區(qū)域顯示了根據(jù)數(shù)據(jù)描繪出來(lái)的圖像,在此區(qū)域內(nèi)R根據(jù)數(shù)據(jù)選擇一個(gè)坐標(biāo)系,通過顯示出來(lái)的坐標(biāo)軸可以看到R使用的坐標(biāo)系。在繪制區(qū)域之外是邊沿區(qū),從底部開始按順時(shí)針方向分別用數(shù)字1到4表示。文字和標(biāo)簽通常顯示在邊沿區(qū)域內(nèi),按照從內(nèi)到外的行數(shù)先后顯示。
添加對(duì)象
在繪制的圖像上還可以繼續(xù)添加若干對(duì)象,下面是幾個(gè)有用的函數(shù),以及對(duì)其功能的說(shuō)明。
?points(x, y, ...),添加點(diǎn)
?lines(x, y, ...),添加線段
?text(x, y, labels, ...),添加文字
?abline(a, b, ...),添加直線y=a+bx
?abline(h=y, ...),添加水平線
?abline(v=x, ...),添加垂直線
?polygon(x, y, ...),添加一個(gè)閉合的多邊形
?segments(x0, y0, x1, y1, ...),畫線段
?arrows(x0, y0, x1, y1, ...),畫箭頭
?symbols(x, y, ...),添加各種符號(hào)
?legend(x, y, legend, ...),添加圖列說(shuō)明
分享名稱:gca函數(shù)python Gcd函數(shù)
網(wǎng)站地址:http://www.chinadenli.net/article28/hijhcp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、網(wǎng)頁(yè)設(shè)計(jì)公司、網(wǎng)站收錄、企業(yè)網(wǎng)站制作、定制網(wǎng)站、App開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容