当前位置: 首页 > news >正文

matplot常备设置

1. 常用包

import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.simplefilter("ignore")

2. 设置全局字体大小

from matplotlib import rcParams
# 设置全局字体大小
rcParams['font.size'] = 20  # 设置全局字体大小

3. 新建图片保存文件夹

# 确保 img 文件夹存在,如果不存在则创建它
img_dir = './img'
if not os.path.exists(img_dir):os.makedirs(img_dir)

4. 调整图像画布空白间距

plt.tight_layout()

5. 多子图

  • 绘制箱线图
import matplotlib.pyplot as plt
import seaborn as sns
# 设置图形大小和布局
plt.figure(figsize=(20, 30))
plt.subplots_adjust(hspace=0.5)# 遍历每个列名,绘制箱线图
for i, column in enumerate(df.columns, 1):plt.subplot(8, 4, i)  # 创建子图,8行4列布局,第 i 个子图sns.boxplot(x=df[column], orient='v')  # 绘制箱线图plt.title(column)  # 设置子图标题plt.tight_layout()  # 调整子图布局,避免重叠
plt.savefig("./img/df_box.png")
plt.show()  # 显示图形
  • 绘制混淆矩阵
for i, best_model in enumerate(best_estimators):plt.figure(figsize=(6, 4))# Predict on test sety_pred = best_model.predict(sx_test)# Compute confusion matrixcm = confusion_matrix(y_test, y_pred)# Plot confusion matrix using seaborn heatmapsns.heatmap(cm, annot=True, fmt='d', cmap='Blues')plt.title(f'Confusion Matrix - {type(best_model).__name__}')plt.xlabel('Predicted labels')plt.ylabel('True labels')# Ensure the plot doesn't overlap with previous plotsplt.tight_layout()# Save the figure if neededplt.savefig(f'./img/ConfusionMatrix_{type(best_model).__name__}2.png')# Show the plotplt.show()

6. 绘制双边y轴

fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp')ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin')
plt.show()

在这里插入图片描述

import matplotlib.pyplot as plt
import numpy as np# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)fig, ax1 = plt.subplots()color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)ax2 = ax1.twinx()  # instantiate a second Axes that shares the same x-axiscolor = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

在这里插入图片描述

Ref

  • matplot.org
    https://matplotlib.org/stable/users/explain/customizing.html

http://www.mrgr.cn/news/60519.html

相关文章:

  • 面向对象编程:从函数到类(6/10)
  • 开源实时数仓的构建
  • vuetify重置样式
  • 深度学习_循环神经网络_预测平安中国股价(文末附带数据集下载链接, 长期有效, 如果有大佬愿意帮忙, 我先在这磕一个,感谢)
  • Maven:详解 clean 和 install 命令的使用
  • Qt:QtCreator使用
  • 【纯血鸿蒙】安装hdc工具
  • MySQL数据库数据类型介绍
  • LSTM模型实现光伏发电功率的预测
  • 机器学习原理与算法图谱问答
  • 中国人寿财险青岛市分公司:创新引领,服务升级
  • 【CSS】边界三角形
  • DEVOPS: 集群伸缩原理
  • MySQL 日志之 binlog 格式 → 关于 MySQL 默认隔离级别的探讨
  • k8s 二进制部署安装(二)
  • Docker 常用命令全解析:提升对雷池社区版的使用经验
  • JAVA是世界上最美丽的语言------拒绝焦虑,赶紧背诵!
  • 【学术会议论文投稿】前端框架巅峰对决:React、Vue与Angular的全面解析与实战指南
  • 【考前冲刺】24下软考考试,无非就这2套模拟卷!
  • 用git上传项目到GitHub(最简单的操作)
  • ZDS 数字股票:携手全球高校,吸引行业精英,共创金融未来
  • 【网络安全零基础入门】一文搞懂Javascript实现Post请求、Ajax请求、输出数据到页面、实现前进后退、文件上传
  • 时代新机遇来袭,创客匠人首届全球创始人 IP 领袖峰会定档
  • JNI概要
  • Flutter-Engine 的定制实践:Text 绘制流程浅析及自定义underline的间距
  • EasyExcel文件导入与导出