如何用Matplotlib自定义精度折线图的线条与图形样式
Matplotlib自定义折线样式实现ViT与TransMix精度对比图
我编写了一段可正常运行的Matplotlib代码,用于生成ViT与TransMix模型的精度对比折线图,但不清楚如何将其修改为指定样式。请问如何在Matplotlib中自定义折线样式?具体需求参考示例图,当前代码及输出如下:
当前代码
import matplotlib.pyplot as plt # Data for different models and their corresponding accuracies models = ['10', '60', '110', '160'] accuracies = [73.2, 75.6, 77.1, 78.3] transmix_accuracies = [74.8, 76.4, 78.2, 79.1] # Create a figure and axis object fig, ax = plt.subplots() # Plot the accuracy of ViT-based models ax.plot(models, accuracies, marker='o', label='ViT') # Plot the accuracy of TransMix models ax.plot(models, transmix_accuracies, marker='o', label='TransMix') # Set the chart title and axis labels #ax.set_title("Improvement of TransMix on ViT-based Models") ax.set_xlabel("Number of Parameters") ax.set_ylabel("ImageNet Top-1 Acc (%)") # Add a legend ax.legend() # Show the plot plt.show()
当前输出图

需求示例图

修改后的代码(匹配示例样式)
import matplotlib.pyplot as plt # 模型参数规模与对应精度数据 models = ['10', '60', '110', '160'] vit_acc = [73.2, 75.6, 77.1, 78.3] transmix_acc = [74.8, 76.4, 78.2, 79.1] # 创建画布与轴对象 fig, ax = plt.subplots(figsize=(8, 5)) # 绘制ViT折线:虚线+空心圆标记 ax.plot(models, vit_acc, linestyle='--', # 虚线样式 marker='o', # 圆形标记 markerfacecolor='white', # 标记填充色为白(空心) markeredgecolor='#1f77b4',# 标记边框色 color='#1f77b4', # 折线颜色 linewidth=2, # 线宽 markersize=8, # 标记大小 label='ViT') # 绘制TransMix折线:实线+实心方块标记 ax.plot(models, transmix_acc, linestyle='-', # 实线样式 marker='s', # 方块标记 markerfacecolor='#ff7f0e',# 标记填充色 color='#ff7f0e', # 折线颜色 linewidth=2, markersize=8, label='TransMix') # 设置坐标轴标签 ax.set_xlabel("Number of Parameters", fontsize=12) ax.set_ylabel("ImageNet Top-1 Acc (%)", fontsize=12) # 添加网格(虚线样式) ax.grid(True, linestyle='--', alpha=0.6) # 调整图例位置 ax.legend(loc='lower right', fontsize=12) # 调整坐标轴刻度字体大小 ax.tick_params(axis='both', labelsize=10) plt.tight_layout() # 自动调整布局,避免标签被截断 plt.show()
关键样式自定义说明
- 折线样式:通过
linestyle(或简写ls)设置,'--'为虚线,'-'为实线,还支持':'点线、'-.'点划线等样式 - 标记样式:
marker参数指定标记形状,'o'为圆形,'s'为正方形,还有'^'三角形、'D'菱形等多种可选 - 标记细节:
markerfacecolor控制标记填充色(设为white即可实现空心效果),markeredgecolor控制标记边框色,markersize调整标记大小 - 折线外观:
color指定折线颜色,linewidth调整线宽 - 辅助元素:
ax.grid()添加网格,通过linestyle和alpha(透明度)调整网格样式;tight_layout()自动优化布局避免元素重叠
内容的提问来源于stack exchange,提问作者Khawar Islam
相关产品推荐
相关产品推荐

