How to start ggplot2 geom_bar from different origin

后端 未结 2 1406
臣服心动
臣服心动 2021-01-06 21:47

I\'d like to start a bar chart at somewhere other than the y = 0. In my case, I want to start the bar chart at y = 1.

As an example, let\'s say that I build a ide

相关标签:
2条回答
  • 2021-01-06 22:02

    You could just change the labels manually, as shown in the other answer. However, I think conceptually the better solution is to define a transformation object that transforms the y axis scale as requested. With that approach, you're literally just modifying the relative baseline for the bar plots, and you can still set breaks and limits as you normally would.

    df <- data.frame(values = c(1,2,0), labels = c("A", "B", "C"))
    
    t_shift <- scales::trans_new("shift",
                                 transform = function(x) {x-1},
                                 inverse = function(x) {x+1})
    
    ggplot(df, aes(x = labels, y = values, fill = labels, colour = labels)) + 
      geom_bar(stat="identity") +
      scale_y_continuous(trans = t_shift)
    

    Setting breaks and limits:

    ggplot(df, aes(x = labels, y = values, fill = labels, colour = labels)) + 
      geom_bar(stat="identity") +
      scale_y_continuous(trans = t_shift,
                         limits = c(-0.5, 2.5),
                         breaks = c(0, 1, 2))
    

    0 讨论(0)
  • 2021-01-06 22:11

    You could use

    ggplot(df, aes(x = labels, y = values-1, fill = labels, colour = labels)) + 
      geom_bar(stat = "identity") +
      scale_y_continuous(name = 'values', 
                         breaks = seq(-1, 1, 0.5), 
                         labels = seq(-1, 1, 0.5) + 1)
    

    0 讨论(0)
提交回复
热议问题