R:自定义曲线中的曲线斜率

时间:2013-07-11 19:07:09

标签: r graph

我想以图形方式表示线的斜率,其中线由公式确定,该公式取一组点的加权平均值。权重基于未表示的外部因素。

我有一个聚合图,x轴上的x变量(价格)和y上的相关(数量)。我试图用另一个图表覆盖那个图表,这个图表只是一组代表数量变化的陡峭程度的线,我们从经验上得出的价格并不等于曲线的斜率。

x轴应该是价格; y应该是音量;曲线的斜率应该是弹性的。我有办法在R吗?

弹性是价格变化1美元的变化。它在不同的价位上有所不同。

df

Category       Price   Volume_Band     Elasticity 

alpha        $1      50,000          -0.5 
beta         $2      100,000         -1 
gamma        $3      200,000         -1.5 
delta        $4      250,000         -2

2 个答案:

答案 0 :(得分:1)

查看数据时,它似乎并不意味着很多曲率,因此直线拟合会产生:

 lm(dat[[4]]~dat[[3]])


Call:
lm(formula = dat[[4]] ~ dat[[3]])

Coefficients:
(Intercept)     dat[[3]]  
     -2e-01       -7e-06  

plot(dat[[3]],dat[[4]])
abline(coef(lm(dat[[4]]~dat[[3]])))

答案 1 :(得分:1)

我仍然不确定,你的图表应该如何。我会给出两个变种,但也许你可以提供一个模拟?

可能性1:

DF <- read.table(text="Category       Price   Volume_Band     Elasticity 
alpha        $1      50,000          -0.5
beta         $2      100,000         -1 
gamma        $3      200,000         -1.5 
delta        $4      250,000         -2",header=TRUE)

DF$Price <- as.numeric(gsub("\\$","",DF$Price))
DF$Volume_Band <- as.numeric(gsub(",","",DF$Volume_Band))

dx <- 0.2
dy <- dx*DF$Elasticity


DF$xstart <- DF$Price-dx
DF$xend <- DF$Price+dx
DF$ystart <- DF$Volume_Band-dy
DF$yend <- DF$Volume_Band+dy


library(ggplot2)

p1 <- ggplot(DF, aes(x=Price, y=Volume_Band)) +
  geom_point() +
  geom_segment(aes(x=xstart,y=ystart,xend=xend,yend=yend))

print(p1)

enter image description here

请注意,斜坡太小而无法看到。

可能性2:

p2 <- ggplot(DF, aes(x=Price, y=Volume_Band)) +
  geom_point(aes(colour=Elasticity),size=3) +
  scale_colour_gradient(high="black",low="red")

print(p2)

enter image description here

相关问题