在r中添加具有堆叠条形图的非线性线

在r中添加具有堆叠条形图的非线性线,r,bar-chart,R,Bar Chart,我想添加一条曲线来拟合此供应成本曲线的暗线(如图中显示的红线)。暗条的高度表示其成本的不确定性范围(costrange)。我使用完全透明值(costtrans)将条形图堆叠到某个级别之上 这是我的代码: 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) cos

我想添加一条曲线来拟合此供应成本曲线的暗线(如图中显示的红线)。暗条的高度表示其成本的不确定性范围(costrange)。我使用完全透明值(costtrans)将条形图堆叠到某个级别之上 这是我的代码:

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)

costtrans我想这真的取决于你想如何计算线

第一种选择是:

# 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)
#将条形图坐标保存到变量中

bp你想用什么统计方法来计算红线的位置?
# 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)