Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ggplot2 display duplicate x axis tick labels

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Any help is appreciated! Thanks!

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading