活动介绍

matplotlib.pyplot绘制图像去除外框线

时间: 2025-07-25 09:13:36 AIGC 浏览: 22
在使用 `matplotlib.pyplot` 绘图时,去除图像的外框线可以通过对坐标轴对象进行操作来实现。外框线通常指的是围绕图表的四条边线,可以通过设置坐标轴的可见性来控制这些边线是否显示。 以下是几种常见的方法来去除图像的外框线: ### 1. 去除所有边框线 如果需要去除图像的所有外框线,可以使用 `spines` 属性来隐藏所有的边框线: ```python import matplotlib.pyplot as plt # 创建一个简单的图像 plt.plot([1, 2, 3], [4, 5, 1]) # 获取当前的坐标轴对象 ax = plt.gca() # 隐藏所有边框线 for spine in ax.spines.values(): spine.set_visible(False) plt.show() ``` ### 2. 去除特定边框线 如果只需要去除某些边框线(例如顶部和右边的边框线),可以单独设置这些边框线的可见性: ```python import matplotlib.pyplot as plt # 创建一个简单的图像 plt.plot([1, 2, 3], [4, 5, 1]) # 获取当前的坐标轴对象 ax = plt.gca() # 隐藏顶部和右边的边框线 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.show() ``` ### 3. 保留底部和左侧边框线 有时可能希望保留底部和左侧的边框线,而去除顶部和右边的边框线。这可以通过以下方式实现: ```python import matplotlib.pyplot as plt # 创建一个简单的图像 plt.plot([1, 2, 3], [4, 5, 1]) # 获取当前的坐标轴对象 ax = plt.gca() # 隐藏顶部和右边的边框线 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) # 确保底部和左侧的边框线可见 ax.spines['bottom'].set_visible(True) ax.spines['left'].set_visible(True) plt.show() ``` ### 4. 自定义边框线样式 如果不想完全隐藏边框线,而是希望自定义其样式(例如颜色或宽度),可以使用以下方法: ```python import matplotlib.pyplot as plt # 创建一个简单的图像 plt.plot([1, 2, 3], [4, 5, 1]) # 获取当前的坐标轴对象 ax = plt.gca() # 自定义边框线的颜色和宽度 for spine in ax.spines.values(): spine.set_edgecolor('red') spine.set_linewidth(2) # 隐藏顶部和右边的边框线 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.show() ``` ### 5. 使用面向对象的 API `matplotlib` 提供了面向对象的 API,可以直接通过 `Figure` 和 `Axes` 对象来操作图表。这种方法在处理复杂的图表时更加灵活和直观: ```python import matplotlib.pyplot as plt # 创建一个 Figure 和 Axes 对象 fig, ax = plt.subplots() # 绘制数据 ax.plot([1, 2, 3], [4, 5, 1]) # 隐藏顶部和右边的边框线 ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) plt.show() ``` 通过这些方法,可以根据具体需求灵活地控制图像的外框线,从而实现更美观的图表效果。 ---
阅读全文

相关推荐

import SimpleITK as sitk import cv2 import numpy as np import matplotlib.pyplot as plt # 读取目标图像 target_img = cv2.imread('./plot_abdomenreg_arrow.jpg') # 读取目标图像 target_img = cv2.cvtColor(target_img, cv2.COLOR_BGR2RGB) # 转换颜色空间 # 读取分割图像 seg_data = sitk.GetArrayFromImage(sitk.ReadImage('./logs/abdomenreg/SegReg_edt/0029_0030_reg/seg_fixed.nii.gz')) # 提取第二维度第40层切片(注意维度顺序) # 根据seg_image.nii.gz的尺寸(96,80,128),应取中间维度 seg_slice = seg_data[:, 40, :] # 得到(96,128)的二维数组 seg_slice = np.flipud(seg_slice) # 上下翻转图像 # 调整分割图像的尺寸以匹配目标图像的尺寸 target_height, target_width, _ = target_img.shape seg_slice_resized = cv2.resize(seg_slice, (target_width, target_height), interpolation=cv2.INTER_NEAREST) # 创建空白轮廓图像 contour_img = np.zeros_like(target_img) # 设置颜色映射 labels = np.unique(seg_slice_resized) colors = plt.cm.jet(np.linspace(0, 1, len(labels))) # 绘制轮廓 for label, color in zip(labels, colors): if label == 0: continue mask = (seg_slice_resized == label).astype(np.uint8) contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours( contour_img, contours, -1, (int(color[0]*255), int(color[1]*255), int(color[2]*255)), 1 ) # 叠加显示 combined = cv2.addWeighted(target_img, 1, contour_img, 1, 0) # 保存结果 cv2.imwrite('contour_overlay.png', cv2.cvtColor(combined, cv2.COLOR_RGB2BGR)) cv2.imwrite('contour_seg.png', cv2.cvtColor(combined, cv2.COLOR_RGB2BGR))把这段代码改为plt作图

import numpy as np import matplotlib.pyplot as plt from matplotlib.patches import Ellipse, Circle # 设置画布 fig, ax = plt.subplots(figsize=(10, 10)) ax.set_xlim(-5, 5) ax.set_ylim(-5, 5) ax.set_aspect('equal') ax.axis('off') ax.set_facecolor('black') # 绘制花蕊(中心部分) center = Circle((0, 0), 0.3, color='gold', zorder=10) ax.add_patch(center) # 彼岸花参数 num_petals = 6 petal_length = 3 petal_width = 0.8 curvature = 0.5 # 绘制花瓣 for i in range(num_petals): angle = 2 * np.pi * i / num_petals x = np.linspace(0, petal_length, 100) y = curvature * x**2 # 旋转花瓣 x_rotated = x * np.cos(angle) - y * np.sin(angle) y_rotated = x * np.sin(angle) + y * np.cos(angle) # 绘制花瓣主体 ax.plot(x_rotated, y_rotated, color='crimson', linewidth=8, zorder=5) # 添加花瓣波浪边缘 wave_x = np.linspace(0, petal_length, 30) wave_y = curvature * wave_x**2 + 0.1 * np.sin(wave_x * 10) wave_x_rotated = wave_x * np.cos(angle) - wave_y * np.sin(angle) wave_y_rotated = wave_x * np.sin(angle) + wave_y * np.cos(angle) ax.plot(wave_x_rotated, wave_y_rotated, color='crimson', linewidth=3, zorder=6) # 绘制花须(从中心向外延伸的细线) for i in range(num_petals * 2): angle = 2 * np.pi * i / (num_petals * 2) length = 0.8 + np.random.random() * 0.4 x_end = length * np.cos(angle) y_end = length * np.sin(angle) ax.plot([0, x_end], [0, y_end], color='gold', linewidth=1, zorder=8) # 添加一些飘落的花瓣 for _ in range(15): x = np.random.uniform(-4, 4) y = np.random.uniform(-4, -1) size = np.random.uniform(0.5, 1.5) angle = np.random.uniform(0, 360) petal = Ellipse((x, y), size, size/2, angle=angle, color='crimson', alpha=0.6) ax.add_patch(petal) # 添加标题 plt.title("彼岸花 - 曼珠沙华", fontsize=16, color='white', y=0.92) plt.tight_layout() plt.show()

import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams # ---------------------- 全局样式设置(确保图表美观统一) ---------------------- rcParams.update({ "font.family": "Arial", # 统一字体为无衬线字体 "font.size": 10, # 基础字体大小 "axes.labelsize": 10, # 坐标轴标签大小 "axes.titlesize": 10, # 子图标题大小 "legend.fontsize": 8, # 图例字体大小 "xtick.labelsize": 8, # x轴刻度标签大小 "ytick.labelsize": 8, # y轴刻度标签大小 "axes.linewidth": 0.8, # 坐标轴边框粗细 "lines.linewidth": 1.2, # 曲线线条粗细 "xtick.major.width": 0.8,# x轴主刻度线粗细 "ytick.major.width": 0.8,# y轴主刻度线粗细 "xtick.minor.width": 0.6,# x轴次刻度线粗细 "ytick.minor.width": 0.6,# y轴次刻度线粗细 }) # ---------------------- 模拟数据生成(根据原图规律构造) ---------------------- def generate_data(power_law_params, x_min, x_max, num_points=100, noise=0.1): """生成符合幂律分布的数据,带误差带""" a, b, exponent = power_law_params # 幂律公式:L = (x / b)^exponent x = np.logspace(np.log10(x_min), np.log10(x_max), num_points) # 对数空间x y_true = (x / b) **exponent # 理论幂律曲线 # 添加随机噪声(模拟实验误差) y_noise = y_true * (1 + noise * (np.random.rand(num_points) - 0.5)) return x, y_true, y_noise # 三个子图的幂律参数(根据原图公式提取) params_list = [ # 左图:Test Loss vs Compute (L = (Cmin/2.3e8)^-0.050) {"power_law": (1, 2.3e8, -0.050), "x_min": 1e-9, "x_max": 1e1, "y_label": "Test Loss", "x_label": "Compute", "x_units": "PF-days, non-embedding", "line_style": "--", "color": "#E67E22"}, # 中图:Test Loss vs Dataset Size (L = (D/5.4e13)^-0.095) {"power_law": (1, 5.4e13, -0.095), "x_min": 1e7, "x_max": 1e9, "y_label": "", "x_label": "Dataset Size", "x_units": "tokens", "line_style": "-", "color": "#3498DB"}, # 右图:Test Loss vs Parameters (L = (N/8.8e13)^-0.076) {"power_law": (1, 8.8e13, -0.076), "x_min": 1e5, "x_max": 1e9, "y_label": "", "x_label": "Parameters", "x_units": "non-embedding", "line_style": "-", "color": "#3498DB"}, ] # ---------------------- 创建多子图并绘制 ---------------------- fig, axes = plt.subplots(1, 3, figsize=(15, 4), dpi=300, gridspec_kw={"wspace": 0.3}) # 1行3列子图,调整间距 for i, ax in enumerate(axes): params = params_list[i] a, b, exponent = params["power_law"] x, y_true, y_noise = generate_data( power_law_params=params["power_law"], x_min=params["x_min"], x_max=params["x_max"], noise=0.05 # 噪声大小(左图误差带较宽,可适当调大) ) # 1. 绘制误差带(浅蓝色半透明区域) if i == 0: # 仅左图显示误差带(原图风格) ax.fill_between( x, y_true * 0.8, # 误差带下边界(原图误差带较宽,手动调整比例) y_true * 1.2, # 误差带上边界 color="#AED6F1", alpha=0.3, edgecolor="none" ) # 叠加噪声散点(模拟实验数据点,左图较密集) ax.scatter(x, y_noise, s=5, color="#85C1E9", alpha=0.5) # 2. 绘制幂律拟合曲线 ax.plot( x, y_true, linestyle=params["line_style"], color=params["color"], linewidth=2, label=rf'$L=({params["x_label"].split()[0]}/{"{:.1e}".format(b).replace("e+", "·10^")})^'f'{{{exponent:.3f}}}$' ) # 3. 右图和中图添加数据点(原图右侧两个图有实心点) if i in [1, 2]: # 均匀采样10个点作为"实验数据点" sample_indices = np.linspace(0, len(x)-1, 10, dtype=int) ax.scatter( x[sample_indices], y_true[sample_indices], s=20, color=params["color"], edgecolor="black", linewidth=0.5, zorder=5 # 置于曲线上方 ) # 4. 设置坐标轴(对数刻度) ax.set_xscale("log") ax.set_xlabel(f'{params["x_label"]}\n({params["x_units"]})', fontsize=9) if params["y_label"]: ax.set_ylabel(params["y_label"], fontsize=9) # 5. 调整坐标轴范围(根据原图视觉效果微调) if i == 0: ax.set_ylim(2, 7) # 左图y轴范围:2-7 else: ax.set_ylim(2.5, 5.8) # 右图和中图y轴范围:2.5-5.8 # 6. 添加图例(公式标签) ax.legend(frameon=True, framealpha=0.9, loc="upper right", fontsize=8) # 7. 美化坐标轴刻度(去除顶部和右侧边框) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) # ---------------------- 保存图片 ---------------------- plt.tight_layout() # 自动调整布局 plt.show() 生成运行结果图

import numpy as np import matplotlib.pyplot as plt from matplotlib import rcParams import matplotlib as mpl # ---------------------- 全局样式设置(确保图表美观统一) ---------------------- # 支持中文显示 - 使用更通用的字体配置 mpl.rcParams["font.family"] = ["WenQuanYi Micro Hei", "Heiti TC", "Arial Unicode MS", "sans-serif"] mpl.rcParams["axes.unicode_minus"] = False # 正确显示负号 # 配置LaTeX字体,确保公式中的中文正常显示 rcParams.update({ "font.size": 10, # 基础字体大小 "axes.labelsize": 10, # 坐标轴标签大小 "axes.titlesize": 10, # 子图标题大小 "legend.fontsize": 8, # 图例字体大小 "xtick.labelsize": 8, # x轴刻度标签大小 "ytick.labelsize": 8, # y轴刻度标签大小 "axes.linewidth": 0.8, # 坐标轴边框粗细 "lines.linewidth": 1.2, # 曲线线条粗细 "xtick.major.width": 0.8, # x轴主刻度线粗细 "ytick.major.width": 0.8, # y轴主刻度线粗细 "xtick.minor.width": 0.6, # x轴次刻度线粗细 "ytick.minor.width": 0.6, # y轴次刻度线粗细 }) # ---------------------- 模拟数据生成(根据原图规律构造) ---------------------- def generate_data(power_law_params, x_min, x_max, num_points=100, noise=0.1): """生成符合幂律分布的数据,带误差带""" _, b, exponent = power_law_params # 幂律公式:L = (x / b)^exponent x = np.logspace(np.log10(x_min), np.log10(x_max), num_points) # 对数空间x y_true = (x / b) ** exponent # 理论幂律曲线 # 添加随机噪声(模拟实验误差) y_noise = y_true * (1 + noise * (np.random.rand(num_points) - 0.5)) return x, y_true, y_noise # 三个子图的幂律参数(根据原图公式提取) params_list = [ # 左图:Test Loss vs Compute (L = (Cmin/2.3e8)^-0.050) {"power_law": (1, 2.3e8, -0.050), "x_min": 1e-9, "x_max": 1e1, "y_label": "测试损失", "x_label": "计算量", "x_units": "PF-days, 非嵌入层", "line_style": "--", "color": "#E67E22"}, # 中图:Test Loss vs Dataset Size (L = (D/5.4e13)^-0.095) {"power_law": (1, 5.4e13, -0.095), "x_min": 1e7, "x_max": 1e9, "y_label": "", "x_label": "数据集大小", "x_units": "tokens", "line_style": "-", "color": "#3498DB"}, # 右图:Test Loss vs Parameters (L = (N/8.8e13)^-0.076) {"power_law": (1, 8.8e13, -0.076), "x_min": 1e5, "x_max": 1e9, "y_label": "", "x_label": "参数数量", "x_units": "非嵌入层", "line_style": "-", "color": "#3498DB"}, ] # ---------------------- 创建多子图并绘制 ---------------------- # 使用constrained_layout替代tight_layout,提供更好的兼容性 fig, axes = plt.subplots(1, 3, figsize=(15, 4), dpi=300, gridspec_kw={"wspace": 0.3}, constrained_layout=True) # 1行3列子图,调整间距 for i, ax in enumerate(axes): params = params_list[i] _, b, exponent = params["power_law"] x, y_true, y_noise = generate_data( power_law_params=params["power_law"], x_min=params["x_min"], x_max=params["x_max"], noise=0.05 # 噪声大小(左图误差带较宽,可适当调大) ) # 1. 绘制误差带(浅蓝色半透明区域) if i == 0: # 仅左图显示误差带(原图风格) ax.fill_between( x, y_true * 0.8, # 误差带下边界 y_true * 1.2, # 误差带上边界 color="#AED6F1", alpha=0.3, edgecolor="none" ) # 叠加噪声散点(模拟实验数据点,左图较密集) ax.scatter(x, y_noise, s=5, color="#85C1E9", alpha=0.5) # 2. 绘制幂律拟合曲线 # 修复公式显示问题,使用更可靠的LaTeX语法 x_label_short = params["x_label"].split()[0] b_formatted = f"{b:.1e}".replace("e+", " \\times 10^{") + "}" formula = rf'$L=({x_label_short}/{b_formatted})^{{{exponent:.3f}}}$' ax.plot( x, y_true, linestyle=params["line_style"], color=params["color"], linewidth=2, label=formula ) # 3. 右图和中图添加数据点 if i in [1, 2]: # 均匀采样10个点作为"实验数据点" sample_indices = np.linspace(0, len(x) - 1, 10, dtype=int) ax.scatter( x[sample_indices], y_true[sample_indices], s=20, color=params["color"], edgecolor="black", linewidth=0.5, zorder=5 # 置于曲线上方 ) # 4. 设置坐标轴(对数刻度) ax.set_xscale("log") ax.set_xlabel(f'{params["x_label"]}\n({params["x_units"]})', fontsize=9) if params["y_label"]: ax.set_ylabel(params["y_label"], fontsize=9) # 5. 调整坐标轴范围 if i == 0: ax.set_ylim(2, 7) # 左图y轴范围:2-7 else: ax.set_ylim(2.5, 5.8) # 右图和中图y轴范围:2.5-5.8 # 6. 添加图例(公式标签) ax.legend(frameon=True, framealpha=0.9, loc="upper right", fontsize=8) # 7. 美化坐标轴刻度(去除顶部和右侧边框) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) # ---------------------- 显示图片 ---------------------- plt.show()