Fork me on GitHub

Matplotlib数据可视化(7):图片展示与保存

In [1]:
import os
import matplotlib.image as mpimg
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 中文字体支持
 

除了作图功能,matplotlib也提供本地图片展示以及保存图片的功能,这两个通能通过imshow()方法和savefig()方法实现。

 

1 图片展示

 

在使用imshow()展示图片前,需要先将图片读取出来。读取图片可以通过pillow库,也可以用matplotlib本身自带的image模块实现。

In [2]:
# 使用pillow库读取图片
img = Image.open(r"./jupyter/matplotlib/images/1.jpg")
fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(121)
ax1.imshow(img)

# 使用matplotlib自带image库读取图片
img = mpimg.imread(r"./jupyter/matplotlib/images/1.jpg")  
ax2 = fig.add_subplot(122)
ax2.imshow(img)


plt.show()
 
 

可以设置关闭坐标轴:

In [3]:
img = mpimg.imread(r"./jupyter/matplotlib/images/1.jpg")  
fig = plt.figure(figsize=(4, 2))
ax1 = fig.add_subplot(111)
ax1.imshow(img)
ax1.axis('off')

plt.show()
 
 

imshow()方法中提供了众多参数以供个性化得展示图片,但我更建议使用pillow等专业的图片处理库先对图片进行处理,然后交由imshow()方法进行展示,以下是使用imshow方法显示灰度图片:

In [4]:
img=Image.open(r"./jupyter/matplotlib/images/1.jpg")
img = np.array(img)
if img.ndim == 3:
    img2 = img[:,:,0]
plt.subplot(321); plt.imshow(img)
plt.subplot(322); plt.imshow(img, cmap = 'gray')  # 无效
plt.subplot(323); plt.imshow(img2)
plt.subplot(324); plt.imshow(img2, cmap = 'gray')  # 灰度
plt.subplot(325); plt.imshow(img2, cmap = plt.cm.gray)  # 与cmap ='gray'等效
plt.subplot(326); plt.imshow(img2, cmap = plt.cm.gray_r)  # 反向灰度
plt.show()
 
 

显示多张图片:

In [5]:
index = 1

fig, axes = plt.subplots(4, 3, figsize=(8, 4), tight_layout=True)
for row in range(4):
    for col in range(3):
        image_name = os.path.join(r'./jupyter/matplotlib/images', str(index)+'.jpg')
        img = plt.imread(image_name)
        axes[row, col].imshow(img)
        axes[row, col].axis('off')
        index += 1
plt.show()
 
 

2 保存图片

当我们使用matplotlib完成作图后,难免有需要将图表保存到本地的需求,这时候就可以使用savefig()方法实现。savefig()方法主要参数如下:

  • fname:保存后图片名
  • dpi:像素
  • quality:用大于1小于100的标量表示图片质量
  • facecolor:前景色
  • edgecolor:边框颜色
  • format:文件格式
  • transparent:是否透明,当没有设置前景色和边框颜色时,如果transparent值为True保存为png格式时为透明
In [6]:
index = 1

fig, axes = plt.subplots(4, 3, figsize=(8, 4), tight_layout=True)
for row in range(4):
    for col in range(3):
        image_name = os.path.join(r'./jupyter/matplotlib/images', str(index)+'.jpg')
        img = plt.imread(image_name)
        axes[row, col].imshow(img)
        axes[row, col].axis('off')
        index += 1
fig.savefig('save_img.jpg', facecolor='grey', edgecolor='red')
plt.show()
 
 

这时候,在本地打开图片如下所示:

 

In [7]:
value= np.arange(6) ** 2
category = range(len(value))

fig = plt.figure(figsize=(8, 4))

# 垂直柱状图
ax1 = fig.add_subplot(121)
ax1.set_title('图1 垂直柱状图')
ax1.bar(x=category, height=value)

# 垂直柱状图
ax2 = fig.add_subplot(122)
ax2.set_title('图2 水平柱状图')
ax2.barh(y=category, width=value)

fig.savefig(r"bar_img.png", transparent=True) # 
plt.show()
 
 

保存后的本地图片bar_img.png如下所示:

 

posted @ 2020-03-15 18:22  奥辰  阅读(11484)  评论(0编辑  收藏  举报