data frame arranges data automatically

...Good day everyone, Im trying to create a plot with some data, my problem is that it is displaying it incorrectly because it is arranging one column automatically. I need it to display from week -8 to week 8 but instead it displays from week - 1 to week 8 , it is arranging everything automatically despite that I put the data in the order that I need. Heres my code and picture of how the plot looks:

      need((nrow(values$mydata)>0),"Favor de procesar consulta")
    colnames(dats) <- c("Weeks","QTY", "Fcst4")
      geom_line(aes(x=Weeks, y=QTY, group='Ventas', colour='Ventas')) +
      geom_line(aes(x=Weeks, y=Fcst4, group='Fcst', colour='Fcst')) +
      geom_point(aes(x=Weeks, y=QTY, group='Ventas', colour='Ventas'))+
      geom_point(aes(x=Weeks, y=Fcst4, group='Fcst', colour='Fcst'))+
        panel.background = element_rect(fill = "#ECEFF4", colour = "#ECEFF4",size = 2, linetype = "solid"),
        panel.grid.major = element_line(size = 0.5, linetype = 'solid',colour = "white"), 
        panel.grid.minor = element_line(size = 0.25, linetype = 'solid',colour = "white"),
        legend.background = element_rect(fill = "#ECEFF4", color = NA),
        legend.key = element_rect(color = "gray", fill = "#ECEFF4"),
        legend.title = element_blank(),
        legend.text = element_text(color = "black"),
        legend.position = "right",
        legend.direction = "vertical",
        plot.background = element_rect(fill = "#ECEFF4"))

thanks a lot


Since your weeks are strings, R sorts them in lexicographic order, this means that the - is not interpreted as minus but just as a character. Try adding an extra column to your data and give it integer values -8 to 8 and sort by that.

Also, even if sorted, ggplot has its own internal sorting and if you give it that list for the x-asis, it will sort it also lexicographically, if you replace the week strings by the numbers - 8 to 8, it should be solved, then add the week strings as labels on the axis instead

1 Like

You can also make Weeks an ordered factor.

vtas = rnorm(16, 3, 1)
fcst <- rnorm(16, 4, 1)
xval <- factor(c("Wk-8","Wk-7","Wk-6","Wk-5","Wk-4","Wk-3","Wk-2","Wk-1","Wk1",
               levels = c("Wk-8","Wk-7","Wk-6","Wk-5","Wk-4","Wk-3","Wk-2","Wk-1","Wk1",
                          "Wk2","Wk3","Wk4","Wk5","Wk6","Wk7","Wk8"), ordered = TRUE)
dats=data.frame(xval, vtas, fcst)
colnames(dats) <- c("Weeks","QTY", "Fcst4")
  geom_line(aes(x=Weeks, y=QTY, group='Ventas')) +
  geom_line(aes(x=Weeks, y=Fcst4, group='Fcst'))

Created on 2019-07-11 by the reprex package (v0.2.1)


thanks a lot for your help :slight_smile:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.