2014-09-05 63 views
2

我想添加一条曲线来拟合此供应成本曲线的暗条(如图中出现的红线)。黑条的高度代表其成本(成本范围)中的不确定性范围。我使用完全透明值(costtrans)堆栈超过一定水平 酒吧这是我的代码:在r中添加带有条形图的非线性线

costtrans<-c(10,10,20,28,30,37,50,50,55,66,67,70) 
costrange<-c(15,30,50,21,50,20,30,40,45,29,30,20) 
cost3<-table(costtrans,costrange) 


cost3<-c(10,15,10,30,20,50,28,21,30,50,37,20,50,30,50,40,55,45,66,29,67,30,70,20) 

costmat <- matrix(data=cost3,ncol=12,byrow=FALSE) 

Dark <- rgb(99/255,99/255,99/250,1) 
Transparent<-rgb(99/255,99/255,99/250,0) 

production<-c(31.6,40.9,3.7,3.7,1,0.3,1.105,0.5,2.3,0.7,0.926,0.9) 
par(xaxs='i',yaxs='i') 
par(mar=c(4, 6, 4, 4)) 

barplot(costmat,production, space=0, main="Supply Curve", col=c(Transparent, Dark), border=NA, xlab="Quantity", xlim=c(0,100),ylim=c(0, 110), ylab="Supply Cost", las=1, bty="l", cex.lab=1.25,axes=FALSE) 
axis(1, at=seq(0,100, by=5), las=1, cex.axis=1.25) 
axis(2, at=seq(0,110, by=10), las=1, cex.axis=1.25) 

形象地描述我所期待的:

http://i.imgur.com/hIZ3P8f.png

+1

什么统计方法你想使用来计算的红线位置? – MrFlick 2014-09-05 07:04:12

回答

2

我猜这真的取决于你如何要计算的行...

一个第一选择是:

# Save the barplot coordinates into a variable 
bp <- barplot(costmat,production, space=0, main="Supply Curve", 
     col=c(Transparent, Dark), border=NA, xlab="Quantity", 
     xlim=c(0,100), ylim=c(0, 110), ylab="Supply Cost", las=1, 
     bty="l", cex.lab=1.25,axes=FALSE) 
axis(1, at=seq(0,100, by=5), las=1, cex.axis=1.25) 
axis(2, at=seq(0,110, by=10), las=1, cex.axis=1.25) 

# Find the mean y value for each box 
mean.cost <- (costmat[1,]+colSums(costmat))/2 
# Add a line through the points 
lines(bp, mean.cost, col="red", lwd=2) 

其中给出

Straight lines through plot

现在,你可以做一些平滑线,使用某种回归

。例如,用黄土回归。

# Perform a LOESS regression 
# To allow for extrapolation, you may want to add 
# control = loess.control(surface = "direct") 
model <- loess(mean.cost~bp, span=1) 
# Predict values in the 0:100 range. 
# Note that, unless you allow extrapolation (see above) 
# by default only values in the range of the original data 
# will be predicted. 
pr <- predict(model, newdata=data.frame(bp=0:100)) 
lines(0:100, pr, col="red", lwd=2) 

LOWSS regression