Python Matplotlib 自定义图例位置与去除边框实现

拾柒
拾柒
发布时间:2026-10-13 | 6人浏览过
原创

本文介绍如何使用Python Matplotlib库自定义图表样式,重点讲解如何去除坐标轴边框以及将图例灵活放置于图表下方。通过具体代码示例,演示了横标线设置、坐标轴刻度隐藏及图例居中定位的方法,帮助开发者实现更简洁专业的数据可视化效果。

Python Matplotlib 去除边框与图例定位实现

为了直观展示实现效果,以下直接提供相关代码示例。


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 7 13:10:21 2018
 
@author: su
"""
 
import numpy as np
import matplotlib.pyplot as plt 
 
n_groups = 2
 
num_list = [0.8,0.80] 
num_list1 = [0.8,0.8] 
num_list2 = [0.9,0.9] 
num_list3 = [0.9,0.9] 
fig, ax = plt.subplots()
plt.grid(True, linestyle = "-", color = "#9dbcd4", linewidth = "0.7",axis= 'y') 
ax = plt.gca()
ax.spines['top'].set_visible(False) #去掉上边框
ax.spines['right'].set_visible(False) #去掉右边框
ax.spines['bottom'].set_visible(False) #去掉上边框
ax.spines['left'].set_visible(False) #去掉右边框
ax.tick_params(axis='y',width=0,length=0)
ax.tick_params(axis='x',width=0,length=0)
index = np.arange(n_groups)
bar_width = 0.5
opacity = 1
rects1 = plt.bar(index, num_list, bar_width/4,alpha=opacity, color='#6B7C85',label='Logistic',hatch='')
rects2 = plt.bar(index + bar_width/4, num_list1, bar_width/4,alpha=opacity,color='#9dbcd4',label='SVM',hatch='/')
rects3= plt.bar(index + bar_width/2, num_list2, bar_width/4,alpha=opacity,color='#1f3d4b',label='CNN',hatch='-')
rects4= plt.bar(index + bar_width*3/4, num_list3, bar_width/4,alpha=opacity,color='#3f829d',label='LSTM',hatch=':')   
# plt.xlabel('Group')
plt.ylabel('Accuracy', fontsize=18)
# plt.title('Scores by group and gender')
plt.xticks(index - 0.3+ bar_width, ('Chinese', 'English'),fontsize =18) 
plt.yticks(fontsize =18) #change the num axis size 
plt.ylim(0.7,0.95) #The ceil 
# 设置legend
plt.legend(loc='center', bbox_to_anchor=(0.5,-0.2),ncol=4,frameon=False,shadow=False)
plt.tight_layout() 
plt.show() 

代码主要实现了两个功能:一是移除图表的上下左右边框,使图形更简洁;二是将图例放置在图表底部中央位置,并设置了横向参考标线。

以上就是Python中通过Matplotlib自由定义图例位置及去除边框的完整实现方式。希望这段代码能为您的图表绘制提供参考,欢迎继续支持本站获取更多技术分享。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表