【问题标题】:Reversing y-axis in an individual ggplot facet在单个 ggplot facet 中反转 y 轴
【发布时间】:2017-05-11 12:28:40
【问题描述】:

我正在绘制一系列不同的数据,这些数据是在同一个人的多个方面测量的。对于某些类型的数据,正值是“好”,而对于某些类型的数据,负值是“好”。后一种类型的变量通常用翻转的 y 轴绘制。是否可以使用 ggplot 修改各个方面的轴方向?

dat <- data.frame(type = rep(c('A', 'B'), each = 10), x = 1:10, y = rnorm(20))

ggplot(dat, aes(x, y)) + geom_point() + facet_wrap( ~ type, scales = 'free_y')

例如,我可以将 B 的 y 轴反转吗?

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我不确定这是否可行,所以我会选择使用 gridExtra 包中的grid.arrange 函数的解决方案。

    library(gridExtra)
    library(ggplot2)
    
    dat <- data.frame(type = rep(c('A', 'B'), each = 10), x = 1:10, y = rnorm(20),
                      stringsAsFactors = FALSE)
    
    p_A <- ggplot(subset(dat, type == 'A'), aes(x, y)) + geom_point() + facet_wrap( ~ type, scales = 'free_y')+
        scale_y_continuous(breaks = c(-1,0,1))
    p_B <- ggplot(subset(dat, type == 'B'), aes(x, y)) + geom_point() + facet_wrap( ~ type, scales = 'free_y')+
        scale_y_reverse(breaks = c(-1,0,1))
    
    grid.arrange(p_A, p_B, nrow = 1)
    

    【讨论】:

    • 感谢您的回答。我有一种感觉,这是唯一不需要大量编码的真正解决方案。我会接受它,因为它可能是可用的最佳解决方案,但我真的希望通过facet_grid 能够很好地推广到更复杂的刻面。
    【解决方案2】:

    这现在也可以使用ggh4xpackagefacetscales 包来实现(请参阅here 了解facetscales 方法):

    library(ggh4x)
    
    dat <- data.frame(type = rep(c('A', 'B'), each = 10), x = 1:10, y = rnorm(20))
    
    scales <- list(
      scale_y_continuous(),
      scale_y_reverse()
      )
    
    ggplot(dat, aes(x, y)) + 
      geom_point() +
      facet_wrap( ~ type, scales = 'free_y') +
      facetted_pos_scales(y = scales)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      • 1970-01-01
      • 2017-07-30
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多