0

I am quite new in ggplot and I have a question to relabelling the x-axis when I use boxplots.

  mat <- as.data.frame(cbind(sample(1:120,5000, replace = TRUE), rnorm(500)))
  colnames(mat) <- c("category","value")
  mat$category <- as.factor(mat$category)

  library(ggplot2)

  p <- ggplot(mat, aes(x=category, y=value)) +
    geom_boxplot() + 
    theme_classic() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
    xlab("Category") + 
    ylab("Value in units")
  p 

The problem is the x-axis as the numbers are difficult to read. My idea is to use a kind of sequence to have fewer numbers or in boxplot case fewer categories written on the x-axis.

My question is where to include something like the following sequence

new_x_labeling = c(1,seq(10,120,5))

I found just answer about changing names in

How to change x-axis tick label names, order and boxplot colour using R ggplot?

but I have no clue how to reduce the number of names.

https://rstudio-pubs-static.s3.amazonaws.com/3364_d1a578f521174152b46b19d0c83cbe7e.html

1 Answer 1

2

Something like that probably:

  ggplot(mat, aes(x=category, y=value)) +
    geom_boxplot() + 
    scale_x_discrete(breaks = c(1, seq(10, 120, 5))) +
    theme_classic() +
    theme(axis.text.x = element_text(angle = 90, hjust = 1)) + 
    labs(x = "Category", y = "Value in units")

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Never thought that was thateasy. I have tried scale_x_discrete( c(1, seq(10, 120, 5))) and nothing happened.
Yes, sometimes the ggplot2 grammar is not so intuitive, as I'd wish it to be.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.