1 回答
TA贡献1891条经验 获得超3个赞
不确定这是否是最好的方法,但我首先缩放ylim到您想要的范围 (-5,5),然后将码值plt.text()从范围 (0,53.3) 缩放到范围 (-5,5) ,相应地调整顶部/底部值plt.text()(从 53.3 到 5,从 0 到 -5)。最后更改ax.scatter()为直接引用您的数据列,因此要在 x 轴上偏移只需添加一个值 10。此外,删除set_aspect(1)。
这样你就不会在一开始就创建一个过大的图形,然后你必须争先恐后地提交。
代码(更改前面的注释# CHANGES HERE !!!:
import matplotlib.pyplot as plt
import pylab as pl
import numpy as np
# Create figure
fig, ax = pl.subplots(figsize=(15,10))
# Set field dimensions
plt.xlim(0, 120) # Field length including endzones
# CHANGES HERE !!!
# set ylim respective to your data
plt.ylim(-5, 5) # field width
# Set field color green
ax.set_facecolor('#79af75')
ax.set_alpha(0.5)
# Print lines
for i in range(0, 120, 10):
plt.axvline(i, color='white', linewidth=3, alpha=0.4, zorder=1)
if i == 10 or i == 110: # Make endzone lines
plt.axvline(i, color='white', linewidth=5, alpha=0.4, zorder=1)
# Paint numbers
yds_from_sideline = 12
for i in range(10, 50, 10):
# CHANGES HERE !!!
# change y values because ylim has changed (top-ylim - yds_from_sideline translated to scale of ylim)
plt.text(i+10, 5-10*(yds_from_sideline/53.3), str(i), color='white', fontsize=20, verticalalignment='bottom', horizontalalignment='center', rotation=180)
plt.text(110-i, 5-10*(yds_from_sideline/53.3), str(i), color='white', fontsize=20, verticalalignment='bottom', horizontalalignment='center', rotation=180)
plt.text(i+10, -5 + 10*(yds_from_sideline/53.3), str(i), color='white', fontsize=20, verticalalignment='bottom', horizontalalignment='center')
plt.text(110-i, -5 + 10*(yds_from_sideline/53.3), str(i), color='white', fontsize=20, verticalalignment='bottom', horizontalalignment='center')
# Paint 50 yard line numbers
# CHANGES HERE !!!
# change y values here as well
plt.text(60, 5-10*(yds_from_sideline/53.3), str(50), color='white', fontsize=20, verticalalignment='bottom', horizontalalignment='center', rotation=180)
plt.text(60, -5+10*(yds_from_sideline/53.3), str(50), color='white', fontsize=20, verticalalignment='bottom', horizontalalignment='center')
# Print something in the endzones
plt.text(5, 0, 'Vikings', color='#4F2683', fontsize=30, verticalalignment='center', horizontalalignment='center', rotation=90)
plt.text(115, 0, 'Opponent', color='black', fontsize=30, verticalalignment='center', horizontalalignment='center', rotation=270)
# Just showing how to set titles and labels
plt.title('The gridiron', fontsize=14)
plt.ylabel('EPA', fontsize=12)
plt.xlabel('Yardline', fontsize=12)
plt.title('The gridiron', fontsize=14)
plt.ylabel('EPA', fontsize=12)
plt.xlabel('Yardline', fontsize=12)
ax.set_yticks(np.arange(-5, 6,1))
# CHANGES HERE !!!
# increase x by 10 to start at x = 10
ax.scatter(x=data['yardline_100']+10,y=data['epa'])
# # Fix the aspect ratio (optional)
# plt.gca().set_aspect(1)
# Display the figure
plt.show()
输出(使用您的示例数据):
添加回答
举报