ggplot: set axis to a certain range

Advertisements

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 :

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)) 

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)) 

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))

Leave a ReplyCancel reply