因此,当我运行脚本时,图例会出现在窗口之外,并且我不确定如何使窗口包括所有内容。我真的不想再缩放图表框的box.width了。我也不确定为什么图例中的每个球员都使用与实际点图所使用的颜色图相反的颜色?
代码:
from bs4 import BeautifulSoup
import requests
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# scrape total stats
url = 'https://www.basketball-reference.com/leagues/NBA_2020_totals.html#totals_stats::pts'
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
stats = soup.find_all('table')
# convert table to dataframe
data = pd.read_html(str(stats))
df = pd.DataFrame(data[0])
df['PTS'] = pd.to_numeric(df['PTS'], errors='coerce')
df_sorted = df.sort_values(by=['PTS'], ascending=False)
print(df_sorted[0:25])
# data needed from dataframe
points = df_sorted[0:25]['PTS']
players = df_sorted[0:25]['Player']
two_pts = df_sorted[0:25]['2P']
three_pts = df_sorted[0:25]['3P']
# visualise data
fig, ax = plt.subplots()
cmap = plt.get_cmap('tab20b')
numDots = len(players)
dotColors = cmap(np.linspace(0., 1., numDots))
area = [10*n for n in range(len(points))]
for x,y,s in zip(two_pts, three_pts, area):
ax.scatter(two_pts, three_pts, s=area, c=dotColors)
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.8, chartBox.height])
# chart
plt.gca().invert_xaxis()
plt.gca().invert_yaxis()
ax.legend(players, loc=5, bbox_to_anchor=(1.6, .5), fontsize=9)
fig.tight_layout()
plt.title('Basketball Stats')
plt.show()