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

Increase space between two discrete values in a ggplot2 plot in R

I am trying to figure out how to add space in a plot between two discrete values on the x-axis. For example, in the plot below, I’d like to keep the same spacing between Setosa and Versicolor but add space between Versiolor and Virginica within the plot (not the axis labels).

data(iris)

library(ggplot2)
ggplot(data = iris, aes(x = Species, y = Sepal.Width)) +
  geom_point() 

>Solution :

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

The easiest way I know of to do this is to make the axis numeric, using custom breaks and labels:

library(ggplot2)

iris %>%
  mutate(Species2 = ifelse(Species == "virginica", 4, as.numeric(Species))) %>%
  ggplot(aes(x = Species2, y = Sepal.Width)) +
  geom_point() +
  scale_x_continuous(breaks = c(1, 2, 4), labels = levels(iris$Species),
                     expand = c(0, 1), name = "Species",
                     minor_breaks = NULL)

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