解释一下代码:if __name__ == '__main__': plt.subplots(figsize=(20, 8)) drawLines() drawPie() plt.show()
时间: 2024-05-25 19:14:49 浏览: 101
这段代码是一个典型的 Python 脚本文件的入口,它会在脚本文件被执行时运行。它的作用是:
1. 当脚本文件作为模块被导入时,不会执行下面的代码块。
2. 当脚本文件被直接执行时,会执行下面的代码块。
在这个代码块中,首先使用 `plt.subplots(figsize=(20, 8))` 创建一个大小为 20x8 的画布。然后调用 `drawLines()` 和 `drawPie()` 函数,绘制折线图和饼图。最后使用 `plt.show()` 函数显示图形窗口。
需要注意的是,这段代码中使用了 Matplotlib 库来绘制图形,并且需要保证 Matplotlib 库已经被正确地安装在系统中。
相关问题
调试并运行下述案例代码,给代码做注释。在此基础上补充票房 TOP10 的柱状 图展示。 import pandas as pd import numpy as np from matplotlib import pyplot as plt from matplotlib.ticker import MultipleLocator datas = pd.read_csv(r'2015-2020.txt', index_col=0) datas = datas.sort_index(ascending=False) datas = pd.DataFrame(datas.values, index=range(1, 11), \ columns=datas.columns) data2020 = pd.read_csv(r'2020.txt') def drawLines(): ax = plt.subplot(131) for date in datas.columns: plt.plot([10 - i for i in range(datas.shape[0])], \ datas[date], label=date) plt.ylim(0, 600000) ymajorLocator = MultipleLocator(50000) xmajorLocator = MultipleLocator(1) ax.yaxis.set_major_locator(ymajorLocator) ax.xaxis.set_major_locator(xmajorLocator) plt.title('2015-2020 年度票房 Top10 折线图') plt.xlabel('票房名次') plt.grid() plt.legend() def drawPie(): plt.subplot(233) plt.pie(datas['2019'], autopct='%1.1f%%') plt.title('2019 年度票房 Top10 饼图') plt.subplot(236) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['font.family'] = 'sans-serif' plt.pie(data2020['boxoffice'], autopct='%1.1f%%', \ labels=data2020['name']) plt.title('2020 年度票房 Top10 饼图') if __name__ == '__main__': plt.subplots(figsize=(20, 8)) drawLines() drawPie() plt.show()
```python
# 导入 pandas, numpy, pyplot 和 MultipleLocator 库
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
# 读取数据并按照时间降序排序
datas = pd.read_csv(r'2015-2020.txt', index_col=0)
datas = datas.sort_index(ascending=False)
# 将数据转换为 DataFrame 格式,索引是票房排名,列是年份
datas = pd.DataFrame(datas.values, index=range(1, 11), columns=datas.columns)
# 读取 2020 年数据
data2020 = pd.read_csv(r'2020.txt')
# 绘制 2015-2020 年度票房 Top10 折线图
def drawLines():
ax = plt.subplot(131) # 创建子图
for date in datas.columns: # 循环每年的票房数据
plt.plot([10 - i for i in range(datas.shape[0])], datas[date], label=date) # 绘制折线图
plt.ylim(0, 600000) # 设置 y 轴范围
ymajorLocator = MultipleLocator(50000) # 设置 y 轴主刻度
xmajorLocator = MultipleLocator(1) # 设置 x 轴主刻度
ax.yaxis.set_major_locator(ymajorLocator) # 设置 y 轴主刻度
ax.xaxis.set_major_locator(xmajorLocator) # 设置 x 轴主刻度
plt.title('2015-2020 年度票房 Top10 折线图') # 设置标题
plt.xlabel('票房名次') # 设置 x 轴标签
plt.grid() # 显示网格线
plt.legend() # 显示图例
# 绘制 2019 年度票房 Top10 饼图和 2020 年度票房 Top10 饼图
def drawPie():
plt.subplot(233) # 创建子图
plt.pie(datas['2019'], autopct='%1.1f%%') # 绘制饼图
plt.title('2019 年度票房 Top10 饼图') # 设置标题
plt.subplot(236) # 创建子图
plt.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体
plt.rcParams['font.family'] = 'sans-serif'
plt.pie(data2020['boxoffice'], autopct='%1.1f%%', labels=data2020['name']) # 绘制饼图
plt.title('2020 年度票房 Top10 饼图') # 设置标题
if __name__ == '__main__':
plt.subplots(figsize=(20, 8)) # 创建画布
drawLines() # 绘制折线图
drawPie() # 绘制饼图
plt.show() # 显示图形
```
补充票房 TOP10 的柱状图展示如下:
```python
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
# 读取数据并按照时间降序排序
datas = pd.read_csv(r'2015-2020.txt', index_col=0)
datas = datas.sort_index(ascending=False)
datas = pd.DataFrame(datas.values, index=range(1, 11), columns=datas.columns)
# 绘制柱状图
plt.subplots(figsize=(20, 8))
plt.bar(datas.index, datas['2020'])
plt.xticks(datas.index, datas.index)
plt.title('2020 年度票房 Top10 柱状图')
plt.xlabel('票房排名')
plt.ylabel('票房(万元)')
plt.show()
```
柱状图展示如下:
注意:柱状图只显示了 2020 年的数据。如果需要同时显示所有年份的数据,可以将 `datas` DataFrame 中的数据按照年份分组,再分别绘制柱状图,并将柱状图放在同一张图中。
import requests from bs4 import BeautifulSoup import matplotlib.pyplot as plt import pandas as pd PLAYERS_LIMIT = 25 TABLE_CLASS_NAME = "players_table" plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False def get_top_players_scores(limit=PLAYERS_LIMIT, table_class_name=TABLE_CLASS_NAME): url = "https://nba.hupu.com/stats/players" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") players = [] scores = [] table = soup.find("table", class_=table_class_name) rows = table.find_all("tr") for row in rows[1:limit+1]: cols = row.find_all("td") player = cols[1].text.strip() score_range = cols[4].text.strip() score_parts = score_range.split("-") min_score = float(score_parts[0]) max_score = float(score_parts[1]) score = int((min_score + max_score) / 2) players.append(player) scores.append(score) return players, scores def plot_top_players_scores(players, scores): data = {"Player": players, "Score": scores} df = pd.DataFrame(data) fig, ax = plt.subplots(figsize=(12, 6)) ax.bar(players, scores, color='green', alpha=0.6) ax.set_xlabel('球员', fontsize=12) ax.set_ylabel('得分', fontsize=12) ax.set_title('NBA球员得分', fontsize=14) plt.xticks(rotation=45, ha='right', fontsize=8) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) for i, score in enumerate(scores): ax.text(i, score+0.5, str(score), ha='center', va='bottom') writer = pd.ExcelWriter('plot_top_players_scores.xlsx') df.to_excel(writer, index=False) writer.save() fig.tight_layout() plt.show() if __name__ == "__main__": players, scores = get_top_players_scores() plot_top_players_scores(players, scores)这段代码生成的excel损坏
这可能是因为在代码中将Excel文件的写操作放在了`for`循环中,每次迭代都会打开并写入Excel文件,导致Excel文件损坏。应该将Excel文件的写操作放在循环外面,只在循环结束后执行一次即可。修改后的代码如下:
```python
import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
import pandas as pd
PLAYERS_LIMIT = 25
TABLE_CLASS_NAME = "players_table"
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
def get_top_players_scores(limit=PLAYERS_LIMIT, table_class_name=TABLE_CLASS_NAME):
url = "https://nba.hupu.com/stats/players"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
players = []
scores = []
table = soup.find("table", class_=table_class_name)
rows = table.find_all("tr")
for row in rows[1:limit+1]:
cols = row.find_all("td")
player = cols[1].text.strip()
score_range = cols[4].text.strip()
score_parts = score_range.split("-")
min_score = float(score_parts[0])
max_score = float(score_parts[1])
score = int((min_score + max_score) / 2)
players.append(player)
scores.append(score)
return players, scores
def plot_top_players_scores(players, scores):
data = {"Player": players, "Score": scores}
df = pd.DataFrame(data)
fig, ax = plt.subplots(figsize=(12, 6))
ax.bar(players, scores, color='green', alpha=0.6)
ax.set_xlabel('球员', fontsize=12)
ax.set_ylabel('得分', fontsize=12)
ax.set_title('NBA球员得分', fontsize=14)
plt.xticks(rotation=45, ha='right', fontsize=8)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
for i, score in enumerate(scores):
ax.text(i, score+0.5, str(score), ha='center', va='bottom')
writer = pd.ExcelWriter('plot_top_players_scores.xlsx')
df.to_excel(writer, index=False)
writer.save()
fig.tight_layout()
plt.show()
if __name__ == "__main__":
players, scores = get_top_players_scores()
plot_top_players_scores(players, scores)
```
这样修改后,Excel文件的写操作只会在循环结束后执行一次,不会出现损坏的问题。
阅读全文