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

ggplot: set axis to a certain range

I am desperately trying to set the scale range from 1 to 5.
I was trying to use ylim(), scale_y_continuous(breaks = seq(1,5,1)) and coord_cartesian(ylim=c(1,5)). How can this be done? Thanks for help!

n <- 10000

test <- data.frame(value = sample(1:5, size = n, replace = TRUE),
                   grp = sample(c("A", "B", "C"), size = n, replace = TRUE),
                   item = sample(c("Item1", "Item2", "Item3", "Item4", "Item5", "Item6"), size = n, replace = TRUE)) 
                   
test %>%
  group_by(item, grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup() %>%
  
  ggplot(aes(x = item, y = mean, group = grp, fill = grp)) +
    geom_col(position = 'dodge') +
    coord_cartesian(ylim=c(1, 5)) +
    coord_flip() 

>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

You could put the ylim inside coord_flip

test %>%
  group_by(item, grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup() %>%
  ggplot(aes(x = item, y = mean, group = grp, fill = grp)) +
  geom_col(position = 'dodge') +
  coord_flip(ylim = c(1, 5)) 

enter image description here

Even better, don’t use coord_flip at all. The default behaviour of geom_col is to make the bars horizontal if you have a categorical y axis and numeric x axis. I always find coord_flip confusing when applying scales and themes, so you can put item on the y axis, mean on the x axis, and stick to using xlim in coord_cartesian instead:

test %>%
  group_by(item, grp) %>%
  summarise(mean = mean(value, na.rm=TRUE)) %>%
  ungroup() %>%
  ggplot(aes(x = mean, y = item, fill = grp)) +
  geom_col(position = 'dodge') +
  coord_cartesian(xlim = c(1, 5)) 

enter image description here

Even better is to use stat = "summary" inside geom_bar, so you don’t need to summarize your data frame at all:

ggplot(test, aes(x = value, y = item, fill = grp)) +
  geom_bar(stat = 'summary', position = 'dodge') +
  coord_cartesian(xlim = c(1, 5))

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