我們有時(shí)候會面臨畫帶有誤差的圖,大致長成下面這個樣子
image.png
代碼為
# -*- 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我們只是用了一下配色,不用是沒關(guān)系的,只是我覺得這種配色比較美觀。
關(guān)鍵的一行代碼是plt.fill_between,就是把陰影畫出來的關(guān)鍵代碼,alpha用來調(diào)節(jié)其透明度。