使用ggplot2的多个方面

时间:2016-12-09 17:24:05

标签: r ggplot2 bar-chart

我有以下数据:

2L      A=>C    6.2
2L      A=>G    13.6
2L      A=>T    6.7
2L      C=>A    5.3
2L      C=>G    3.8
2L      C=>T    12.6
2L      G=>A    14.1
2L      G=>C    4.3
2L      G=>T    5.5
2L      T=>A    10.3
2L      T=>C    12.6
2L      T=>G    5
2R      A=>C    5.1
2R      A=>G    11.2
2R      A=>T    9.4
2R      C=>A    4
2R      C=>G    4
2R      C=>T    11.6
2R      G=>A    17
2R      G=>C    4
2R      G=>T    6.9
2R      T=>A    9.1
2R      T=>C    12
2R      T=>G    5.8

我正在尝试为每个色谱柱(data[,1])制作单独的条形图。我可以在同一块情节上绘制它:

library(ggplot2)

snps<-read.table("new.txt", header = FALSE)
chroms<-snps[,1]
trans<-snps[,2]
freq<-snps[,3]


ggplot(snps, aes(x = trans, y = freq, group = chroms, fill = chroms)) + geom_bar(position="dodge",stat="identity")

enter image description here

但是我希望能够分别绘制每个色谱图。当我尝试使用facet_grid时,我收到以下错误消息:

ggplot(snps, aes(x = trans, y = freq, group = chroms, fill = chroms)) + 
geom_bar(position="dodge",stat="identity") + facet_grid(chroms ~ .)

---

Error in combine_vars(data, params$plot_env, rows, drop = params$drop) : 
At least one layer must contain all variables used for facetting

如何在此示例中正确使用facetting?

2 个答案:

答案 0 :(得分:1)

我认为你不应该为你的变量创建额外的数据帧。 这应该有效:

snps<-read.table("new.txt", header = FALSE)
colnames(snps)=c("chroms","trans","freq")
ggplot(snps, aes(x = trans, y = freq, group = chroms, fill = chroms)) + geom_bar(position="dodge",stat="identity")+facet_grid(chroms~.)

它给了我: enter image description here

答案 1 :(得分:1)

facet_wrap()替代方案:

df <- read.table(text="chroms trans freq
2L      A=>C    6.2
2L      A=>G    13.6
2L      A=>T    6.7
2L      C=>A    5.3
2L      C=>G    3.8
2L      C=>T    12.6
2L      G=>A    14.1
2L      G=>C    4.3
2L      G=>T    5.5
2L      T=>A    10.3
2L      T=>C    12.6
2L      T=>G    5
2R      A=>C    5.1
2R      A=>G    11.2
2R      A=>T    9.4
2R      C=>A    4
2R      C=>G    4
2R      C=>T    11.6
2R      G=>A    17
2R      G=>C    4
2R      G=>T    6.9
2R      T=>A    9.1
2R      T=>C    12
2R      T=>G    5.8", header=TRUE, stringsAsFactors=FALSE)


ggplot(df, aes(trans, freq, group=chroms, fill=chroms)) + 
  geom_bar(position="dodge", stat="identity") +
  facet_wrap(~chroms) +
  scale_y_continuous(expand=c(0,0)) +
  ggthemes::scale_fill_tableau() +
  theme_minimal() +
  theme(panel.grid.major.x=element_blank()) +
  theme(panel.spacing=unit(2, "lines")) +
  theme(legend.position="none")

enter image description here