How can I plot with 2 different y-axes?

前端 未结 6 1329
遥遥无期
遥遥无期 2020-11-22 08:46

I would like superimpose two scatter plots in R so that each set of points has its own (different) y-axis (i.e., in positions 2 and 4 on the figure) but the points appear su

6条回答
  •  爱一瞬间的悲伤
    2020-11-22 09:14

    If you can give up the scales/axis labels, you can rescale the data to (0, 1) interval. This works for example for different 'wiggle' trakcs on chromosomes, when you're generally interested in local correlations between the tracks and they have different scales (coverage in thousands, Fst 0-1).

    # rescale numeric vector into (0, 1) interval
    # clip everything outside the range 
    rescale <- function(vec, lims=range(vec), clip=c(0, 1)) {
      # find the coeficients of transforming linear equation
      # that maps the lims range to (0, 1)
      slope <- (1 - 0) / (lims[2] - lims[1])
      intercept <- - slope * lims[1]
    
      xformed <- slope * vec + intercept
    
      # do the clipping
      xformed[xformed < 0] <- clip[1]
      xformed[xformed > 1] <- clip[2]
    
      xformed
    }
    

    Then, having a data frame with chrom, position, coverage and fst columns, you can do something like:

    ggplot(d, aes(position)) + 
      geom_line(aes(y = rescale(fst))) + 
      geom_line(aes(y = rescale(coverage))) +
      facet_wrap(~chrom)
    

    The advantage of this is that you're not limited to two trakcs.

提交回复
热议问题