Search code examples
rggplot2yaxis

How do I adjust the y-axis scale when drawing with ggplot2?


The code provides the data and the functions required for ggplot drawing, but the drawn bar chart y-axis is not equidistant, which makes me confused. Please scholars answer.

col1 <- c('SO','MO','EO','YO','RO')
col2 <- c('J','J','J','J','J',
          'F','F','F','F','F',
          'M','M','M','M','M',
          'G','G','G','G','G')
col3 <- c('0.92966','0.94522','0.93311','0.995222',
          '0.966463','0.975725','0.976464','0.9635321',
          '0.980223','0.9124456','0.991678','0.973444',
          '0.910789','0.922','0.993444','0.956555',
          '0.923132','0.987222','0.900556','0.932228')
data <- data.frame(col1,col2,col3)
library(ggplot2)
ggplot(data, aes(x=col1, y=col3,fill=col2)) + 
  labs(x = "col1", y = "col3")+
  geom_bar(stat = 'identity', position=position_dodge())+
  scale_fill_discrete(
    breaks = c("J","F","M",'G'))+
  theme(legend.title = element_text( size=12, face="bold"),
        legend.text = element_text(size =12),
        axis.title.x = element_text(size = 13, face="bold"),
        axis.title.y = element_text(size = 13, face="bold"),
        axis.text.x = element_text(size = 12, face="bold"),
        axis.text.y = element_text(size = 12,face="bold"))+
  scale_x_discrete(limits = c('SO','MO','EO','YO','RO'))

How to draw a bar chart with y-axis range of 0.9-1 and equal spacing?


Solution

  • You could change the range by using a coord_cartesian with ylim like this:

    library(ggplot2)
    ggplot(data, aes(x=col1, y=as.numeric(col3), fill=col2)) + 
      labs(x = "col1", y = "col3")+
      geom_bar(stat = 'identity', position=position_dodge())+
      scale_fill_discrete(
        breaks = c("J","F","M",'G'))+
      theme(legend.title = element_text( size=12, face="bold"),
            legend.text = element_text(size =12),
            axis.title.x = element_text(size = 13, face="bold"),
            axis.title.y = element_text(size = 13, face="bold"),
            axis.text.x = element_text(size = 12, face="bold"),
            axis.text.y = element_text(size = 12,face="bold"))+
      scale_x_discrete(limits = c('SO','MO','EO','YO','RO')) +
      coord_cartesian(ylim = c(0.9, 1)) +
      scale_y_continuous(expand = c(0, 0))
    

    Created on 2022-11-18 with reprex v2.0.2