同时使用两个比例格式化ggplot轴

时间:2015-07-14 08:49:16

标签: r plot ggplot2 scale

我想要产生的是一个图(ggplot2),其中两个变量在同一个x轴上绘制,但是一个在上面,另一个在x轴下面,但是(1)上下是绝对值,(2)非科学记数法。这两项任务都可以使用包abs中的函数(1)comma和(2)scales单独实现:

## data
rlength <- structure(list(Mapping = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("antisense", 
"sense"), class = "factor"), readlength = c(30L, 35L, 31L, 28L, 
34L, 32L, 24L, 22L, 27L, 29L, 25L, 23L, 26L, 33L, 20L, 21L, 26L, 
35L, 27L, 28L, 25L, 29L, 32L, 31L, 30L, 34L, 33L, 22L, 23L, 21L, 
20L, 24L), N = c(99854L, 7238L, 53523L, 146805L, 8743L, 28161L, 
18934L, 6872L, 117191L, 136601L, 35895L, 11110L, 70936L, 14873L, 
3807L, 4900L, 139893L, 74330L, 177004L, 173025L, 90852L, 137917L, 
76706L, 84552L, 104221L, 72414L, 73268L, 48112L, 51317L, 40638L, 
34869L, 64274L)), row.names = c(NA, -32L), class = "data.frame", .Names = c("Mapping", 
"readlength", "N"))

library(plyr)
library(ggplot2)
library(scales)

## plot1
ggplot(rlength, aes(x=readlength))+
   theme_minimal() +
  geom_bar(subset=.(Mapping == "sense"), aes(y=N), stat="identity", colour="blue", fill="blue")+
  geom_bar(subset=.(Mapping == "antisense"), aes(y=-N), stat="identity", colour="red", fill="red")+
  geom_hline(yintercept=0, linetype=2)+
  scale_y_continuous(labels=abs)

## plot2
ggplot(rlength, aes(x=readlength))+
   theme_minimal() +
  geom_bar(subset=.(Mapping == "sense"), aes(y=N), stat="identity", colour="blue", fill="blue")+
  geom_bar(subset=.(Mapping == "antisense"), aes(y=-N), stat="identity", colour="red", fill="red")+
  geom_hline(yintercept=0, linetype=2)+
  scale_y_continuous(labels=comma)

但是尝试一起使用2会引发错误:

ggplot(rlength, aes(x=readlength))+
   theme_minimal() +
  geom_bar(subset=.(Mapping == "sense"), aes(y=N), stat="identity", colour="blue", fill="blue")+
  geom_bar(subset=.(Mapping == "antisense"), aes(y=-N), stat="identity", colour="red", fill="red")+
  geom_hline(yintercept=0, linetype=2)+
  scale_y_continuous(labels=comma, labels=abs)

Error in continuous_scale(c("y", "ymin", "ymax", "yend", "yintercept",  : 
  formal argument "labels" matched by multiple actual arguments

问题是: 是否可以组合这两种格式化程序功能?如果没有,我们非常感谢如何制作我正在寻找的情节。

1 个答案:

答案 0 :(得分:1)

我找到了答案,而且很明显。所需要的只是一个结合abscomma的新功能:

abs_commma <- function(x) {comma(abs(x))}

ggplot(rlength, aes(x=readlength))+
   theme_minimal() +
  geom_bar(subset=.(Mapping == "sense"), aes(y=N), stat="identity", colour="blue", fill="blue")+
  geom_bar(subset=.(Mapping == "antisense"), aes(y=-N), stat="identity", colour="red", fill="red")+
  geom_hline(yintercept=0, linetype=2)+
  scale_y_continuous(labels=abs_commma)

我将它放在这里供将来参考。