Reverse x axis in ecdf plot using ggplot

1.3k views Asked by At

How can I plot the reverse xaxis for ecdf using ggplot() function (not the qplot() function)?

The following code does not work:

 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

Without scale_x_reverse( lim=c(15,0)) the plot would be like the following:

enter image description here

1

There are 1 answers

2
Andre Silva On BEST ANSWER

Reversing the order of the x axis will make the ecdf function to recalculate the cumulative probabilities over the new range (as stated by tonytonov).

This is a workaround:

#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