Invert x-axis to ecdf slice with ggplot

How can I build a reverse xaxis for ecdf using a function ggplot()

(not a function qplot()

)?

The following code doesn't 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, the scale_x_reverse( lim=c(15,0))

graph will look like this:

enter image description here

+3


source to share


1 answer


Reversing the order of the x-axis will cause ecdf to recalculate the cumulative probabilities in the new range (as indicated by the tonitones).

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

+2


source







All Articles