rggplot2boxplot

Boxplot: How to convert x-axis to continuous value scale?


How can I convert the x-axis to have continuous values. In the proposed example, I would like to have the boxplot at 0 away from those associated with 2.5 and 3. I don't want to have 3 equidistant boxplots.

I thank you in advance for your help.

library(ggplot2)

set.seed(123)
data <- data.frame(
  Group = rep(c("0", "2.5", "3"), each = 50),
  Value = c(rnorm(50), rnorm(50, mean = 1), rnorm(50, mean = 2))
)
ggplot(data, aes(x = Group, y = Value, group = Group)) + 
  geom_boxplot(fill = "lightblue", orientation = "x") + 
  scale_x_discrete(limits = as.factor(c("0", "2.5", "3"))) + 
  labs(x = "numbers", y = "Value") +
  theme(axis.text.x = element_text(angle = 0, hjust = .5))

Solution

  • Perhaps omit the quotes for the Group variable, and replace scale_x_discrete() with scale_x_continuous().

    set.seed(123)
    data <- data.frame(
      Group = rep(c(0, 2.5, 3), each = 50),
      Value = c(rnorm(50), rnorm(50, mean = 1), rnorm(50, mean = 2))
    )
    
    ggplot(data, aes(x = Group, y = Value, group = Group)) + 
      geom_boxplot(fill = "lightblue", orientation = "x") + 
      scale_x_continuous(breaks = c(0, 2.5, 3)) + 
      labs(x = "numbers", y = "Value") +
      theme(axis.text.x = element_text(angle = 0, hjust = .5))
    

    enter image description here