如何在R中的切面图中找到ggplot X轴图例中的断点范围?

时间:2017-12-19 19:44:21

标签: r ggplot2

我想要在下面绘制数据d。我想只放置每个chr方面的开始和结束位置,但我不知道如何找到范围(每种chr类型的最小值和最大值)。有人可以帮帮我吗?

d<- structure(list(chr = c("chr10", "chr10", "chr10", "chr11", 
"chr11", 
"chr11", "chr12", "chr12", "chr12", "chr13", "chr13", "chr13", 
"chr14", "chr14", "chr14", "chr15", "chr15", "chr15", "chr16", 
"chr16", "chr16", "chr1", "chr1", "chr1", "chr2", "chr2", "chr2", 
"chr3", "chr3", "chr3", "chr4", "chr4", "chr4", "chr5", "chr5", 
"chr5", "chr6", "chr6", "chr6", "chr7", "chr7", "chr7", "chr8", 
"chr8", "chr8", "chr9", "chr9", "chr9"), start = c(6, 14, 19, 
3, 10, 16, 60, 73, 80, 4, 11, 27, 67, 75, 81, 2, 7, 15, 13, 99, 
142, 1, 8, 21, 49, 53, 78, 92, 121, 165, 35, 42, 47, 5, 9, 17, 
12, 20, 34, 44, 51, 56, 61, 66, 94, 18, 31, 37), stop = c(6, 
14, 19, 3, 10, 16, 60, 73, 80, 4, 11, 27, 67, 75, 81, 2, 7, 15, 
13, 99, 142, 1, 8, 21, 49, 53, 78, 92, 121, 165, 35, 42, 47, 
5, 9, 17, 12, 20, 34, 44, 51, 56, 61, 66, 94, 18, 31, 37), density = 
c(10, 
4, 1, 13, 1, 1, 18, 48, 526, 3, 1, 1, 13, 74, 177, 1, 3, 5, 9432, 
3, 5, 1, 32, 1, 60, 4, 3, 2, 1, 10, 4, 10, 6, 6, 2, 3, 5, 65220, 
11136, 1, 25, 36, 5, 6, 1, 4, 7, 11)), .Names = c("chr", "start", 
"stop", "density"), row.names = c(NA, -48L), class = "data.frame")

这是绘制我的数据的代码:

  d$chr <- factor(d$chr, levels = c('chr1', 'chr2', 'chr3', 'chr4', 
  'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 
  'chr13', 'chr14', 'chr15', 'chr16'))
  library(ggplot2)
  ggplot(d, aes(start, density)) +
  geom_line(alpha = 0.9) +
  facet_grid(. ~ chr) +
  # facet_grid(. ~ chr, scales = "free_x")  +
  labs(title = "Density profiles along the chromosomes",
       x = "Coordinate, bp",
       y = "Density") +
  theme(plot.title = element_text(hjust = 0.5)) 

1 个答案:

答案 0 :(得分:1)

以下黑客是否适合您?

ggplot(d, aes(start, density)) +
  geom_line(alpha = 0.9) +

  # each facet's x-axis range should be based on the facet's actual range
  facet_grid(. ~ chr, scales = "free_x")  + 

  # expand must be set to (0, 0) so that the limits are exactly the range
  # limits from the data frame
  scale_x_continuous(expand = c(0, 0),
                     breaks = function(x) x) +

  labs(title = "Density profiles along the chromosomes",
       x = "Coordinate, bp",
       y = "Density") +
  theme(plot.title = element_text(hjust = 0.5),

        # align x-axis labels inwards for easier reading
        axis.text.x = element_text(hjust = c(-0.1, 1.1))) 

plot

这是基于breaks参数在scale_x_continuous()中可以采用的最后一个选项:

  

其中一个:

     
      
  • 没有休息的空白
  •   
  • waiver()用于由转换对象计算的默认中断
  •   
  • 位置的数字向量
  •   
  • 将限制作为输入并将中断作为输出
  • 的函数   

将两个标签向内对齐的技巧来自this SO answer