for i, j in enumerate(y_data): plt.text(x = i, y = j + 3, s = str(j), ha = "center")
时间: 2024-03-31 20:36:51 浏览: 41
这是在柱状图上添加数据标签的代码。具体来说,for 循环遍历 y_data 列表中的每一个元素 j,使用 enumerate() 函数获取到每个元素的索引 i 和值 j。然后使用 plt.text() 方法在柱状图上添加标签。其中,x 参数为柱状图的 x 坐标,i 即为 x 坐标,y 参数为柱状图的 y 坐标,j+3 即为 y 坐标,s 参数为标签的文本内容,这里使用 str(j) 将数值转为字符串进行显示,ha 参数为水平对齐方式,这里设置为 "center" 表示居中对齐。通过修改参数,可以自定义标签的样式和位置。
相关问题
import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split # 读取训练集和测试集数据 train_data = pd.read_csv(r'C:\ADULT\Titanic\train.csv') test_data = pd.read_csv(r'C:\ADULT\Titanic\test.csv') # 统计训练集和测试集缺失值数目 print(train_data.isnull().sum()) print(test_data.isnull().sum()) # 处理 Age, Fare 和 Embarked 缺失值 most_lists = ['Age', 'Fare', 'Embarked'] for col in most_lists: train_data[col] = train_data[col].fillna(train_data[col].mode()[0]) test_data[col] = test_data[col].fillna(test_data[col].mode()[0]) # 拆分 X, Y 数据并将分类变量 one-hot 编码 y_train_data = train_data['Survived'] features = ['Pclass', 'Age', 'SibSp', 'Parch', 'Fare', 'Sex', 'Embarked'] X_train_data = pd.get_dummies(train_data[features]) X_test_data = pd.get_dummies(test_data[features]) # 合并训练集 Y 和 X 数据,并创建乘客信息分类变量 train_data_selected = pd.concat([y_train_data, X_train_data], axis=1) print(train_data_selected) cate_features = ['Pclass', 'SibSp', 'Parch', 'Sex', 'Embarked', 'Age_category', 'Fare_category'] train_data['Age_category'] = pd.cut(train_data.Fare, bins=range(0, 100, 10)).astype(str) train_data['Fare_category'] = pd.cut(train_data.Fare, bins=list(range(-20, 110, 20)) + [800]).astype(str) print(train_data) # 统计各分类变量的分布并作出可视化呈现 plt.figure(figsize=(18, 16)) plt.subplots_adjust(hspace=0.3, wspace=0.3) for i, cate_feature in enumerate(cate_features): plt.subplot(7, 2, 2 * i + 1) sns.histplot(x=cate_feature, data=train_data, stat="density") plt.xlabel(cate_feature) plt.ylabel('Density') plt.subplot(7, 2, 2 * i + 2) sns.lineplot(x=cate_feature, y='Survived', data=train_data) plt.xlabel(cate_feature) plt.ylabel('Survived') plt.show() # 绘制点状的相关系数热图 plt.figure(figsize=(12, 8)) sns.heatmap(train_data_selected.corr(), vmin=-1, vmax=1, annot=True) plt.show() sourceRow = 891 output = pd.DataFrame({'PassengerId': test_data.PassengerId, 'Survived': predictions}) output.head() # 保存结果 output.to_csv('gender_submission.csv', index=False) print(output) train_X, test_X, train_y, test_y = train_test_split(X_train_data, y_train_data, train_size=0.8, random_state=42) print("随机森林分类结果") y_pred_train1 = train_data.predict(train_X) y_pred_test1 = train_data.predict(test_X) accuracy_train1 = accuracy_score(train_y, y_pred_train1) accuracy_test1 = accuracy_score(test_y, y_pred_test1) print("训练集——随机森林分类器准确率为:", accuracy_train1) print("测试集——随机森林分类器准确率为:", accuracy_train1)
在你的代码中,你正在尝试从 `train_data` 对象上调用一个名为 "predict" 的方法,而 `train_data` 实际上是一个 DataFrame 对象,该对象并没有 "predict" 方法。你应该使用你之前定义的随机森林分类器对象 `RandomForestClassifier` 来进行预测。请将以下代码:
```
y_pred_train1 = train_data.predict(train_X)
y_pred_test1 = train_data.predict(test_X)
```
更改为:
```
# 定义随机森林分类器对象
rfc = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
# 在训练数据上拟合分类器
rfc.fit(train_X, train_y)
# 在训练集和测试集上进行预测
y_pred_train1 = rfc.predict(train_X)
y_pred_test1 = rfc.predict(test_X)
```
这将使用你之前定义的随机森林分类器对象 `rfc` 来进行预测。同时,你需要使用 `rfc.fit(train_X, train_y)` 在训练数据上拟合分类器,然后使用 `rfc.predict(train_X)` 和 `rfc.predict(test_X)` 在训练集和测试集上进行预测。
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文件的写操作只会在循环结束后执行一次,不会出现损坏的问题。
阅读全文