我们有时候会面临画带有误差的图,大致长成下面这个样子
代码为
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 5 21:12:17 2020
@author: x1c
"""
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set()
#plt.plot(x,(y1+y2)/2,color = 'red')
#plt.fill_between(x, y1, y2, color='red', alpha=0.1)
def plot_error(x,y,label,color='gray'):
# Input y=[y1,y2,...] yi.shape = [m,1]
Y = np.zeros((y[0].shape[0],len(y)))
y_mean = 0
for i in range(len(y)):
y_mean += y[i]
Y[:,i] = y[i][:,0]
#print(Y)
y_mean /= len(y)
y_max = np.max(Y,axis=1)
y_min = np.min(Y,axis=1)
#print(y_max)
x = x.squeeze()
y_mean = y_mean.squeeze()
y_max = y_max.squeeze()
y_min = y_min.squeeze()
plt.plot(x,y_mean,label=label,color=color)
plt.fill_between(x,y_min,y_max,color=color,alpha=0.1)
plt.show()
x = np.arange(0,10)
y1 = x+x**2+(np.random.random(10,)-1/2)*100
y2 = x+x**2+(np.random.random(10,)-1/2)*100
x = x.reshape(-1,1)
y1 = y1.reshape(-1,1)
y2 = y2.reshape(-1,1)
plot_error(x,[y1,y2],label='test',color='gray')
稍加解读,seaborn我们只是用了一下配色,不用是没关系的,只是我觉得这种配色比较美观。
关键的一行代码是plt.fill_between,就是把阴影画出来的关键代码,alpha用来调节其透明度。