【Python】plt.savefig()保存图片不完整,x轴标签被截断

今天在用Python的plt.savefig()函数保存图片到本地时,发现保存下来的图片不完整,x轴标签被截断了。经过一番搜索,找到了解决方法:
加上参数bbox_inches = 'tight'即可:

plt.savefig(r"figure.png",bbox_inches = 'tight')
根据报错Traceback (most recent call last): File "D:\whw\实验\大论文模型\RGE-UNet\RGE-UNet\ShapeClass_Train.py", line 324, in <module> loss_k,train_k, valid_k=k_fold(k,image_dir,num_epochs,device,batch_size) #,optimizer,loss,net File "D:\whw\实验\大论文模型\RGE-UNet\RGE-UNet\ShapeClass_Train.py", line 178, in k_fold loss_min, train_acc_max, test_acc_max = train(i, train_loader, val_loader, net, loss, optimizer, device, num_epochs) File "D:\whw\实验\大论文模型\RGE-UNet\RGE-UNet\ShapeClass_Train.py", line 287, in train plt.plot(x1, y4, 'o-') File "C:\software\python\anaconda3\envs\ResUnet\lib\site-packages\matplotlib\pyplot.py", line 3578, in plot return gca().plot( File "C:\software\python\anaconda3\envs\ResUnet\lib\site-packages\matplotlib\axes\_axes.py", line 1721, in plot lines = [*self._get_lines(self, *args, data=data, **kwargs)] File "C:\software\python\anaconda3\envs\ResUnet\lib\site-packages\matplotlib\axes\_base.py", line 303, in __call__ yield from self._plot_args( File "C:\software\python\anaconda3\envs\ResUnet\lib\site-packages\matplotlib\axes\_base.py", line 499, in _plot_args raise ValueError(f"x and y must have same first dimension, but " ValueError: x and y must have same first dimension, but have shapes (2,) and (1,),修改代码 x1 = range(0, num_epochs) y4 = train_acc_max_l[i] y5 = train_l_min_l[i] y2= test_acc_max_l[i] y3= test_l_min_l[i] plt.figure(figsize=(10,1)) plt.subplot(2, 1, 1) plt.plot(x1, y4, 'o-') plt.title('Class_'+str(i+1)+' Train accuracy vs. epoches') plt.ylabel('Train accuracy') plt.subplot(2, 1, 2) plt.plot(x1, y5, '.-') plt.xlabel('Class Train loss vs. epoches') plt.ylabel('Train loss') plt.tight_layout() plt.savefig('result/losspic/resnet/train_'+str(i+1)+'.png') plt.close() # plt.show() plt.figure(figsize=(10, 1)) plt.subplot(2, 1, 1) plt.plot(x1, y2, 'o-') plt.title('Class Val accuracy vs. epoches') plt.ylabel('Val accuracy') plt.subplot(2, 1, 2) plt.plot(x1, y3, '.-') plt.xlabel('Class_'+str(i+1)+' Val loss vs. epoches') plt.ylabel('Val loss') plt.tight_layout() plt.savefig('result/losspic/resnet/val_' + str(i + 1) + '.png') plt.close() # plt.show()
03-08
``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import SelectKBest, f_classif from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score, classification_report, roc_curve, auc, confusion_matrix import statsmodels.api as sm from sklearn.metrics import precision_score, roc_curve plt.style.use('ggplot') # 读取数据 file_path = r'C:\Users\29930\Desktop\插补数据.csv' data = pd.read_csv(file_path,encoding='GBK') data['性别'] = data['性别'].map({'男': 0, '女': 1}) # 编码性别列 arr = data.to_numpy() # 转换为NumPy数组 # 查看前几行数据 print(data.head()) # 检查是否有缺失值 print(data.isnull().sum()) # 填充缺失值(如果有的话) data.ffill(inplace=True) # 分离特征和目标变量 X = data.drop(columns=['慢阻肺']) # 假设第一列为COPD标签 y = data['慢阻肺'] # 标准化数值型特征 scaler = StandardScaler() X_scaled = scaler.fit_transform(X) # 将标准化后的数据转回DataFrame格式以便后续操作 X_scaled_df = pd.DataFrame(X_scaled, columns=X.columns) # 使用SelectKBest进行单变量选择 selector = SelectKBest(score_func=f_classif, k='all') # 先部选出来查看得分情况 fit = selector.fit(X_scaled_df, y) # 打印每个特征的重要性评分 feature_scores = pd.DataFrame(list(zip(X_scaled_df.columns, fit.scores_)), columns=['Feature','Score']) feature_scores.sort_values(by='Score', ascending=False, inplace=True) print(feature_scores) # 绘制特征重要性图 plt.figure(figsize=(10, 6)) sns.barplot(x="Score", y="Feature", data=feature_scores) plt.title('Feature Importance Scores') plt.show() # 选择最重要的几个特征 selected_features = feature_scores[feature_scores.Score >= feature_scores.Score.quantile(0.75)].Feature.tolist() # 选取前75%分位数以上的特征 X_selected = X_scaled_df[selected_features] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X_selected, y, test_size=0.2, random_state=42) # 定义逻辑回归模型 logreg = LogisticRegression(solver='liblinear') # 超参数调优 - 这里我们只对正则化强度C做网格搜索 param_grid = {'C': [0.01, 0.1, 1, 10, 100]} grid_search = GridSearchCV(logreg, param_grid, cv=5, scoring='accuracy') grid_search.fit(X_train, y_train) # 输出最佳参数组合及对应的成绩 best_logreg = grid_search.best_estimator_ print("Best parameters:", grid_search.best_params_) print("Best CV Score:", grid_search.best_score_) # 在测试集上应用最优模型 y_pred = best_logreg.predict(X_test) # 计算性能指标 acc = accuracy_score(y_test, y_pred) report = classification_report(y_test, y_pred) conf_mat = confusion_matrix(y_test, y_pred) print(f"Accuracy: {acc:.4f}") print(report) # 绘制混淆矩阵热力图 plt.figure(figsize=(8, 6)) sns.heatmap(conf_mat, annot=True, fmt='d', cmap='Blues') plt.xlabel('Predicted Label') plt.ylabel('True Label') plt.title('Confusion Matrix Heatmap') plt.show() # ROC曲线 fpr, tpr, _ = roc_curve(y_test, best_logreg.decision_function(X_test)) roc_auc = auc(fpr, tpr) plt.figure(figsize=(8, 6)) plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC Curve (area = {roc_auc:.2f})') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver Operating Characteristic') plt.legend(loc="lower right") plt.show() # 添加常数项 X_const = sm.add_constant(X_selected) # 构建OLS线性回归模型(用于展示线性关系) model = sm.Logit(y, X_const).fit() print(model.summary()) # 获取最终模型方程 coefs = list(best_logreg.coef_[0]) + [best_logreg.intercept_[0]] features_with_intercept = ['const'] + selected_features formula_parts = [] for coef, feat in zip(coefs, features_with_intercept): formula_parts.append(f"{coef:+.4f}*{feat}") final_formula = " + ".join(formula_parts) print("\nFinal Early Screening Formula:") print(final_formula.replace('+', ' + ').replace('-', ' - '))```输出的重要特征图像中的变量标签显示中文
最新发布
03-28
<think>嗯,用户提供的代码在绘制特征重要性图像时,变量标签无法显示中文。我需要分析可能的原因并提供解决方案。首先,Matplotlib默认支持中文字体,这会导致中文标签显示为方框或乱码。用户可能没有正确设置中文字体,或者在绘图时没有指定字体参数。 接下来,我需要回忆Matplotlib中处理中文显示的方法。通常需要设置字体,可以使用`plt.rcParams`来指定支持中文的字体,例如SimHei。另外,在代码中可能还需要调整Seaborn的字体设置,因为Seaborn基于Matplotlib,可能继承相同的设置。 用户代码中已经导入了Matplotlib和Seaborn,并且在绘图前使用了`plt.style.use('ggplot')`,但可能没有配置字体。需要检查是否有字体设置的部分。例如,添加以下代码: ```python plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签 plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号 ``` 另外,还要确保系统中安装了相应的中文字体。比如,SimHei是Windows系统中的字体,如果用户使用其他操作系统,可能需要同的字体名称,比如在Linux中使用`Noto Sans CJK JP`等。 查看用户的代码,发现没有设置字体的部分。因此,问题出在这里。解决方案是在导入Matplotlib后立即设置这些参数,确保所有后续绘图都能正确显示中文。 此外,用户在绘制特征重要性图时,使用了Seaborn的barplot,因此需要确认Seaborn是否应用了这些设置。一般来说,设置Matplotlib的rcParams应该会影响Seaborn的字体显示。 最后,提醒用户在保存图像时,如果使用savefig,可能需要额外参数,比如`bbox_inches='tight'`来防止标签截断。但用户当前的问题可能只是显示问题,所以先解决字体设置即可。</think>好的,针对代码中输出的重要特征图像无法显示中文标签的问题,以下是分步解决方案: $\boxed{原因分析}$ 1. Matplotlib默认使用英文字体库 2. 未显式指定支持中文的字体配置 $\boxed{解决方法}$ 在代码头部导入matplotlib后添加以下字体配置: ```python # 新增中文显示配置(放在plt.style.use之后) plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体为黑体 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示异常 sns.set(font='SimHei') # 设置Seaborn字体 ``` $\boxed{修改后的代码段落}$ ```python plt.style.use('ggplot') # 新增中文显示配置(必须放在plt.style.use之后) plt.rcParams['font.sans-serif'] = ['SimHei'] # Windows系统字体 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示异常 sns.set(font='SimHei') # 设置Seaborn字体 # 读取数据 file_path = r'C:\Users\29930\Desktop\插补数据.csv' ...(后续代码保持变)... ``` $\boxed{注意事项}$ 1. 若使用Mac/Linux系统,需改用系统支持的中文字体,例如: ```python plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] # Mac # 或 plt.rcParams['font.sans-serif'] = ['WenQuanYi Zen Hei'] # Linux ``` 2. 确保系统已安装对应字体,可通过以下命令查看可用字体: ```python import matplotlib.font_manager print([f.name for f in matplotlib.font_manager.fontManager.ttflist if f.name.startswith('Sim')]) ``` $\boxed{原理说明}$ 通过显式指定中文字体配置,覆盖了Matplotlib的默认设置,使坐标标签和文本元素能够正确解析Unicode中文编码。`axes.unicode_minus`参数用于解决负号可能显示为方框的问题。 修改后输出的特征重要性图将正常显示中文标签,提升可视化结果的易读性。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值