我在10个月内在特定品牌的8个不同国家/地区创造了收入。 data.frame看起来类似于:
Month Country Revenue
1 Fr 1100
1 Uk 900
1 It 800
2 Fr 1200
2 Uk 1050
2 It 900
3 Fr 1350
3 Uk 1200
3 It 1000
4 Fr 1300
4 Uk 1250
4 It 950
# Code to replicate the above mentioned data frame
data.Frame <- data.frame(Month = c(1,1,1,2,2,2,3,3,3,4,4,4),Country = c("Fr","Uk","It"),
Revenue = c(1100,900,800,1200,1050,900,1350,1200,1000,1300,1250,950))
现在我有一个每个国家/地区每个国家的收入的条形图
plot_rev <- ggplot(data.Frame, aes(Month, Revenue, fill = Country, ymax = max(Revenue)+100,
title = "Revenue (in 1000€) per Country per Month in 2014"))
plot_rev+geom_bar(stat = "identity", position = "dodge")
我还使用函数
计算了化合物年增长率(CAGR)annual.growth.rate <- function(a){
T1 <- max(a$Month) - min(a$Month)+1
FV <- a[which(a$Month == max(a$Month)),"Revenue"]
SV <- a[which(a$Month == min(a$Month)),"Revenue"]
cagr <- ((FV/SV)^(1/T1)) -1
}
gr <- data.Frame(x = unique(data.Frame$Country),y= 1:length(unique(data.Frame$Country)))
colnames(gr) <- c("country","cagr")
for(i in 1: nrow(gr)){
gr[i,2] <- round(annual.growth.rate(data.Frame[which(data.Frame$Country == gr[i,1]),]),digits = 2)
}
# Growth Curve Function
FV = PV*(1+cagr)^T
我的问题是,是否可以在现有条形图上绘制生长曲线图层?如果是,那怎么样?如果没有,那么可以单独进行吗?
我试图查看包curve3d
中的emdbook
,但它只需要2个独立变量。
提前感谢您的帮助!!
答案 0 :(得分:0)
我不确定我的答案,但可能只是你想要这个吗?
#your function
annual.growth.rate <- function(a){
T1 <- max(a$Month) - min(a$Month)+1
FV <- a[which(a$Month == max(a$Month)),"Revenue"]
SV <- a[which(a$Month == min(a$Month)),"Revenue"]
cagr <- ((FV/SV)^(1/T1)) -1
}
# recalculate gr, but faster and more efficient (no loop)
library(plyr)
gr=ddply(data.frame,c("Country"),function(x) cagr=round(annual.growth.rate(x),digits = 2))
#get T as well (although it miht even be shorter to put into your funtion return(list(T1=T1,...))
grT=ddply(data.frame,c("Country"),function(x) T1=(max(x$Month) - min(x$Month)+1))
# Growth Curve Function => just get the values and plot these??
data.frame$FV = data.frame$Revenue*(1+gr$V1)^grT$V1
# plot values with line?
ggplot(data.frame, aes(Month, Revenue, fill = Country, ymax = max(Revenue)+100,title = "Revenue (in 1000€) per Country per Month in 2014"))+
geom_bar(stat = "identity", position = "dodge")+
geom_line(aes(Month,FV,col=Country),size=2)