Python利用matplotlib生成图片背景及图例透明的效果

yipeiwu_com5年前Python基础

前言

最近工作中遇到一个需求,在使用matplotlib生成图片,想要背景透明,而且图例部分也显示透明效果,通过查找相关资料找到了大概的设置方法,特此记录,方便自己或者有需要的朋友们参考学习。

示例代码

# coding=utf-8 
# matplotlib背景透明示例图 
# python 3.5 
 
import numpy as np 
import matplotlib.pyplot as plt 
from pylab import mpl 
import scipy.stats as stats 
 
# 设置中文字体 
mpl.rcParams['font.sans-serif'] = ['SimHei'] 
 
 
def autolabel(rects): 
 # attach some text labels 
 for rect in rects: 
  height = rect.get_height() 
  # 设置标注文字及位置 
  ax.text(rect.get_x() + rect.get_width() / 2, 0.03 + height, '%.4f' % height, ha='center', va='bottom') 
 
# 数据 
testData = [[0.87, 0.40, 0.56], 
   [0.97, 0.50, 0.33], 
   [0.88, 0.30, 0.44], 
   [0.25, 0.23, 0.17], 
   [0.73, 0.33, 0.45]] 
 
N = 3 
width = 0.5 
ind = np.arange(width, width*6*N, width*6) 
 
fig, ax = plt.subplots() 
rectsTest1 = ax.bar(ind, (testData[0][0], testData[0][1], testData[0][2]), width, color=(0, 0, 1, 1), edgecolor=(0, 0, 1, 1)) 
 
rectsTest2 = ax.bar(ind + width, (testData[1][0], testData[1][1], testData[1][2]), width, color=(1, 0, 0, 1), edgecolor=(1, 0, 0, 1)) 
 
rectsTest3 = ax.bar(ind + 2*width, (testData[2][0], testData[2][1], testData[2][2]), width, color=(0, 1, 0, 1), edgecolor=(0, 1, 0, 1)) 
 
rectsTest4 = ax.bar(ind + 3*width, (testData[3][0], testData[3][1], testData[3][2]), width, color=(1, 0.6471, 0, 1), edgecolor=(1, 0.6471, 0, 1)) 
 
rectsTest5 = ax.bar(ind + 4*width, (testData[4][0], testData[4][1], testData[4][2]), width, color=(0.5804, 0, 0.8275, 1), edgecolor=(0.5804, 0, 0.8275, 1)) 
 
ax.set_xlim(0, 9.5) 
ax.set_ylim(0, 1.4) 
ax.set_ylabel('数值') 
ax.yaxis.grid(True) 
ax.set_xticks(ind + width * 2.5) 
ax.set_xticklabels(('P', 'R', 'F')) 
 
# 设置图例 
legend = ax.legend((rectsTest1, rectsTest2, rectsTest3, rectsTest4, rectsTest5), ('test1', 'test2', 'test3', 'test4', 'test5')) 
frame = legend.get_frame() 
frame.set_alpha(1) 
frame.set_facecolor('none') # 设置图例legend背景透明 
 
# 给每个数据矩形标注数值 
autolabel(rectsTest1) 
autolabel(rectsTest2) 
autolabel(rectsTest3) 
autolabel(rectsTest4) 
autolabel(rectsTest5) 
 
plt.savefig('C:/Users/XX/Desktop/test.png', format='png', bbox_inches='tight', transparent=True, dpi=600) # bbox_inches='tight'

图片边界空白紧致, 背景透明 

效果可能在网页上看不出来,但还是把图片贴上来吧。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用python能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

在Pycharm中自动添加时间日期作者等信息的方法

在Pycharm中自动添加时间日期作者等信息的方法

1.按照下面路径以此打开 File→→Settings→→Editor→→File and code Templates 右侧找到Python Script,如下图 2.设置相...

Python自定义函数的创建、调用和函数的参数详解

函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。函数能提高应用的模块性,和代码的重复利用率。你已经知道Python提供了许多内建函数,比如print()。但你也可以自己...

Python中IPYTHON入门实例

本文实例讲述了Python中IPYTHON用法。分享给大家供大家参考。具体分析如下: 1. 使用TAB补全功能 2. 配置IPYTHON .ipython目录中的是一个名为ipy_use...

python冒泡排序算法的实现代码

1.算法描述:(1)共循环 n-1 次(2)每次循环中,如果 前面的数大于后面的数,就交换(3)设置一个标签,如果上次没有交换,就说明这个是已经好了的。 2.python冒泡排序代码 复...

浅析PyTorch中nn.Module的使用

torch.nn.Modules 相当于是对网络某种层的封装,包括网络结构以及网络参数和一些操作 torch.nn.Module 是所有神经网络单元的基类 查看源码 初始化部分:...