Daibingh Less is more, slow is fast.

python 数据可视化


Matplotlib 篇

基本曲线

import matplotlib.pyplot as plt
# 提前创建句柄形式
fig, ax = plt.subplots()  # 后期通过句柄修改图和轴属性
ax.plot(x,y)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('x-y')
plt.show()
fig.savefig('plot.png')  # 保存图片

# 另一种方式
plt.figure()  # plt.gcf(), plt.gca() 获取活动句柄
plt.plot(x,y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('x-y')
plt.show()
plt.savefig('plot.png')  # 保存图片

子图

# 方式 1
img_target = plt.imread('./作业文件2/target.jpg').astype('float32') / 255.0 
set_figsize([6*2, 5*3])
fig, ax = plt.subplots(3,2)
preds = []
titles = ['nearest', 'bilinear', 'bicubic'] 
methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC]

for i in range(3):
    pred = cv2.resize(img, None, fx=3, fy=3, interpolation=methods[i])
    pred[pred>1]=1.0
    pred[pred<0]=0.0
    preds.append(pred)
    ax[i][0].imshow(pred)
    ax[i][0].set_xticks([])
    ax[i][0].set_yticks([])
    ax[i][0].set_title(titles[i])
    ax[i][1].imshow(img)
    ax[i][1].set_xticks([])
    ax[i][1].set_yticks([])
    ax[i][1].set_title('target image')
plt.tight_layout()  # 紧凑布局

# 方式 2
set_figsize([6*2,5*2])  # 自编函数
plt.figure()

plt.gcf().add_subplot(221)
plt.imshow(img_sr_y.astype('uint8'))
plt.title('稀疏表示超分图像(Y通道)')
no_ticks()  # 自编函数
plt.gcf().add_subplot(222)
plt.imshow(img_hr_y)
plt.title('高分辨率真实图像(Y通道)')
no_ticks()
plt.gcf().add_subplot(223)
img_sr[img_sr<0]=0
img_sr[img_sr>1]=1
plt.imshow(img_sr)
plt.title('稀疏表示超分图像(RGB)')
no_ticks()
plt.gcf().add_subplot(224)
plt.imshow(img_hr)
plt.title('高分辨率真实图像(RGB)')
no_ticks()

plt.tight_layout()

条形图

plt.rcParams['figure.figsize'] = [6*2, 5]
ind = np.arange(2)
plt.figure()
plt.gcf().add_subplot(121)
plt.bar(ind, [mse_bc, mse_sr], width=.3)  # 修改 xticklabel 第一步,bar(ind, ..)
plt.gca().set_xticks(ind)  # 修改 xticklabel 第二步,set_xticks(ind)
plt.gca().set_xticklabels(['bicubic','Sparse Representation'])  # 修改 xticklabel 第三步,set_xticklabels(..)
plt.title('MSE')
plt.gcf().add_subplot(122)
plt.bar(ind, [psnr_bc, psnr_sr], width=.3)
plt.gca().set_xticks(ind)
plt.gca().set_xticklabels(['bicubic','Sparse Representation'])
plt.title('PSNR')
plt.tight_layout()

显示图片

def no_ticks():
    plt.gca().set_xticks([])
    plt.gca().set_yticks([])
    
img = plt.imread('./作业文件2/input.jpg')
plt.imshow(img)
no_ticks()
plt.title('input image')

绘制动态曲线

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
x = np.arange(0, 5, .1)
for i in range (100):
	y = np.sin(x)+np.random.rand(x.shape[0])
	ax.plot(x,y, 'r-.')
	plt.pause(.01)
	del ax.lines[0]  # or ax.cla()

plt.show()

其它设置

  • 设置轴 ticks, ticklabels
      # 不显示 ticks
      def no_ticks():
          plt.gca().set_xticks([])
          plt.gca().set_yticks([])
        
      # 自定义 ticks, ticklabels    
      plt.gca().set_xticks([1,2,3]])
      plt.gca().set_xticklabels(['a','b','c'], rotation=90)
    
  • set figure size in jupyter notebook
      def set_figsize(size):
          plt.rcParams['figure.figsize'] = size
        
      # 另一种方法
      plt.figure(figsize=[6*2,5*2])
    
  • matplotlib 显示中文
      plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
      plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
    

Heat Map

import seaborn as sn
sn.heatmap(feat_df.corr(), annot=True)

# another way
plt.matshow(mat)

使用 tensorboardX

# install
pip install tensorboardX
from tensorboardX import SummaryWriter
import numpy as np
import matplotlib.pyplot as plt

writer = SummaryWriter(log_dir='lod_dir')
for i in range(100):
    y1 = np.sin(i)
    y2 = np.cos(i)
    writer.add_scalar('y1', y1, i)  # 添加一个变量
    writer.add_scalar('y2', y2, i)
    writer.add_scalars('group', {'y1': y1, 'y2': y2}, i)  # 添加多个变量
img = plt.imread('lena.png')
writer.add_image('image', img, 0, dataformats='HWC')  # 添加图片
writer.close()

# tensorboard --logdir=./log
# ├─lod_dir
#     └─events.out.tfevents.1562547045.DESKTOP-NSAGR5C
#     └─group
#        ├─y1
#        | └─events.out.tfevents.1562547055.DESKTOP-NSAGR5C
#        └─y2
#          └─events.out.tfevents.1562547055.DESKTOP-NSAGR5C

Similar Posts

下一篇 爬虫小结

Comments