Home > Software design >  ggplot2 display duplicate x axis tick labels
ggplot2 display duplicate x axis tick labels

Time:12-05

I have the following tibble:

library(tibble)
library(ggplot2)

df <- tibble(
  Time = c('J-17', 'J', 'A', 'S', 'O', 'N', 'D', 'J-18', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', 'J-19', 'F'),
  Measurement = c(6.8, 6.7, 6.86, 6.63, 6.86, 7.61, 6.99, 7.48, 6.96, 7.22, 7.27, 7.19, 7.58, 7.46, 6.6, 6.97, 7.05, 7.41, 7.91, 6.38, 6.69)
)

# Added an index to df
df$Index <- 1:nrow(df)

I'm plotting like this:

    ggplot(df, aes(
      x = df$Index,
      y = df$Measurement,
    ))  
      geom_hline(yintercept = mean(df$Measurement))  
      geom_line()  
      scale_x_discrete(expand = c(0,0), labels = df$Time)  
      theme_classic()  
      geom_point()

The labels aren't showing on the x axis at all. Am I using labels in scale_x_discrete correctly?

Time contains duplicate values and I want to keep those and keep the same order as in the df

Any help is appreciated! Thanks!

CodePudding user response:

You don't need to use $ inside aes, since you already referencing the data.frame. Also it is scale_x_continuous, since the variable for x is Index.

ggplot(
  data = df, aes(
    x = Index,
    y = Measurement))  
  geom_hline(aes(yintercept = mean(Measurement)))  
  geom_line()  
  scale_x_continuous(expand = c(0,0),breaks = df$Index,labels = df$Time )  
  theme_classic()  
  geom_point()

enter image description here

  • Related