rggplot2

Change labels of a ggplot2 chart


enter image description here

I have the hither graph where on the x-axis you can see it says "Semana 1", "Semana 2", and so on; meaning "Week 1", "Week 2", etc.

I'd like them to say exactly

"20-Dic","28-Dic","03-Ene","10-Ene", "21-Ene", "28-Ene", "2-Feb", "10-Feb"

respectively.

The problem is that if I change the names of the entries in the .csv the order in the graph gets shuffled in a lexicographic manner, as in here:

enter image description here

On the other hand I've been trying to change the names with an ad-hoc solution and I haven't been able to do much.

I was hoping to find an elegant solution. I'm not very well versed in R.

Thanks in advance.


Solution

  • You can pass your desired labels in as a character vector to the labels argument of ggplot2::scale_x_discrete() if you are using {ggplot2}.

    weeks <- c(1:9)
    df <- data.frame(
      week = paste("Semana", weeks),
      value = dnorm(weeks, mean = 5)
    )
    df
    #>       week        value
    #> 1 Semana 1 0.0001338302
    #> 2 Semana 2 0.0044318484
    #> 3 Semana 3 0.0539909665
    #> 4 Semana 4 0.2419707245
    #> 5 Semana 5 0.3989422804
    #> 6 Semana 6 0.2419707245
    #> 7 Semana 7 0.0539909665
    #> 8 Semana 8 0.0044318484
    #> 9 Semana 9 0.0001338302
    
    p <- ggplot2::ggplot(
      data = df,
      ggplot2::aes(x = week, y = value)
    ) +
      ggplot2::geom_point()
    p
    

    
    p +
      ggplot2::scale_x_discrete(
        labels = c(
          "20-Dic", "28-Dic", "03-Ene",
          "10-Ene", "21-Ene", "28-Ene",
          "2-Feb", "10-Feb", "20-Oct"
        )
      )
    

    Created on 2024-11-05 with reprex v2.1.1.9000