使用ggplot在ecdf图中反转x轴

时间:2014-12-07 22:46:18

标签: r graph plot ggplot2 ecdf

如何使用ggplot()函数(而不是qplot()函数)为ecdf绘制反向x轴?

以下代码不起作用:

 test1 <- 
structure(list(ID = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L), ProductType = c("productA",
"productA", "productA", "productA", "productA", "productA", "productA",
"productA", "productA", "productA", "productB", "productB", "productB",
"productB", "productB", "productB", "productB", "productB", "productB",
"productB"), ConsumptionDays = structure(c(29, 98, 164, 96, 233,
14, 12, 264, 97, 47, 27, 133, 28, 63, 420, 105, 67, 160, 22,
41), class = "difftime", units = "days")), .Names = c("ID", "ProductType",
"ConsumptionDays"), row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 51L, 52L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L
), class = "data.frame")

ggplot(data=test1, aes(as.numeric(ConsumptionDays)/30 , color=ProductType)) +
  geom_line(stat='ecdf', size = 0.9 ) +
  scale_x_reverse( lim=c(15,0))

enter image description here

如果没有scale_x_reverse( lim=c(15,0)),情节将如下所示:

enter image description here

1 个答案:

答案 0 :(得分:2)

反转x轴的顺序将使ecdf函数重新计算新范围内的累积概率(如tonytonov所述)。

这是一种解决方法:

#Consumption Months
df = data.frame(test1, C_months = as.numeric(test1$ConsumptionDays/30))
#Order from smallest to greatest based on Comsumption Months
df = df[with(df, order(ProductType,C_months)), ]

#Get cumulative observations in a scale from 0 to 1
subA = subset(df,df$ProductType == "productA")
seqA = c(seq(1/nrow(subA),1,1/nrow(subA)))
subB = subset(df,df$ProductType == "productB")
seqB = c(seq(1/nrow(subB),1,1/nrow(subB)))
cumulated = c(seqA,seqB)
#Add cumulative observations to data.frame
df = data.frame(df,cum=cumulated)

ggplot(data=df, aes(C_months,cum, group=ProductType, color=ProductType)) +
  geom_line(size=1.5) + 
  scale_x_reverse(limits=c(15,0),"Comsumption Months") +
  ylab("Cumulative of observations") +
  theme_bw()

enter image description here