如何在matplotlib图底部显示残差

5 投票
3 回答
26673 浏览
提问于 2025-04-18 09:06

我想要制作这个图表。图表底部显示了误差。你能告诉我这是怎么做的吗?

我在StackOverflow上找到一个例子,但它是用R语言写的。如何在R中创建一个显示预测模型、数据和残差的图表

3 个回答

-1

我觉得你想要的错误条(error bars)是这样的,像这个pylab_examples 的示例代码:errorbar_demo.py

你可以添加一个额外的子图,然后把带有错误条的点画出来。

补充:图之间没有边框:

from pylab import *
subplots_adjust(hspace=0.,wspace=0.)
subplot(211)
imshow(rand(100,100), cmap=cm.BuPu_r)
subplot(212)
imshow(rand(100,100), cmap=cm.BuPu_r)
show()
0

这是一篇旧帖子,不过因为它是关于制作底部残差图的热门内容,我觉得有必要对@jaydeepsb的代码进行一些修改,这样它就可以直接运行了。

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

# Data
x = np.arange(1,10,0.2)
ynoise = x*np.random.rand(len(x)) 
ydata = x**2 + ynoise

Fofx = lambda x,a,b,c: a*x**2+b*x+c
p, cov = curve_fit(Fofx,x,ydata)

# Upper plot
fig1 = plt.figure(1)
frame1 = fig1.add_axes((.1,.3,.8,.6))

plt.plot(x,ydata,'.b') 
plt.plot(x,Fofx(x,*p),'-r') 

frame1.set_xticklabels([]) 
plt.grid()

# Residual plot
difference = Fofx(x,*p) - ydata
frame2 = fig1.add_axes((.1,.1,.8,.2))        
plt.plot(x,difference,'or')
plt.grid()
15

你可以在Matplotlib中通过使用 add_axes 来创建这样的图表。下面是一个例子。

from scipy.optimize import curve_fit
#Data
x = arange(1,10,0.2)
ynoise = x*numpy.random.rand(len(x)) 
#Noise; noise is scaled by x, in order to it be noticable on a x-squared function
ydata = x**2 + ynoise #Noisy data

#Model
Fofx = lambda x,a,b,c: a*x**2+b*x+c
#Best fit parameters
p, cov = curve_fit(Fofx,x,ydata)

#PLOT
fig1 = figure(1)
#Plot Data-model
frame1=fig1.add_axes((.1,.3,.8,.6))
#xstart, ystart, xend, yend [units are fraction of the image frame, from bottom left corner]
plot(x,ydata,'.b') #Noisy data
plot(x,Fofx(x,*p),'-r') #Best fit model
frame1.set_xticklabels([]) #Remove x-tic labels for the first frame
grid()

#Residual plot
difference = Fofx(x,*p) - ydata
frame2=fig1.add_axes((.1,.1,.8,.2))        
plot(x,difference,'or')
grid()

在底部绘制残差图,通过使用 <code>add_axes</code> 添加另一个框架

撰写回答