【问题标题】:How to start ggplot2 geom_bar from different origin如何从不同的来源启动 ggplot2 geom_bar
【发布时间】:2018-02-14 19:12:06
【问题描述】:

我想在 y = 0 以外的位置开始条形图。就我而言,我想在 y = 1 处开始条形图。

举个例子,假设我用 ggplot2 构建了一个身份geom_bar() 图表。

df <- data.frame(values = c(1, 2, 0),
                 labels = c("A", "B", "C"))

library(ggplot2)
ggplot(df, aes(x = labels, y = values, fill = labels, colour = labels)) + 
  geom_bar(stat="identity")

现在,我不是在问如何设置比例或轴限制。我希望代表值小于 1 的条从 y = 1 向下流动。

它需要看起来像这样......但有不同的 y 轴:

有什么建议吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以手动更改标签,如另一个答案所示。但是,我认为从概念上讲,更好的解决方案是定义一个转换对象,根据要求转换 y 轴比例。使用这种方法,您实际上只是在修改条形图的相对基线,您仍然可以像往常一样设置中断和限制。

    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)
    

    设置中断和限制:

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

    【讨论】:

      【解决方案2】:

      你可以使用

      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)
      

      【讨论】:

        猜你喜欢
        • 2021-12-05
        • 2012-06-15
        • 1970-01-01
        • 2018-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        • 2017-10-17
        相关资源
        最近更新 更多