ggplot2-将所有数据标签添加到带面的堆叠条形图的一部分

时间:2018-11-13 21:26:49

标签: r ggplot2

我有一个数据框架,该数据框架在堆叠的条形图中看起来非常不平衡。我需要给数据加标签,并且我正在考虑将所有堆叠数据的标签放在一个堆栈中,这样它们就可以清晰地看到。

以下是与我的数据接近的示例:

year <- c(2011,2012,2012,2013,2013,2011,2011,2012,2012,2013,2013)
type <- c('A','A','A','A','A','B','B','B','B','B','B')
ind <- c(1,0,1,0,1,0,1,0,1,0,1)
n <- c(9000,5,9000,5,9000,10,10000,10,10000,10,10000)
pct<-c(1,0.01,0.99,0.01,0.99,0.01,0.99,0.01,0.99,0.01,0.99)

df <- data.frame(year, type, ind, n, pct)
df$ind <- as.factor(df$ind)
rm(year, type, ind, n, pct)

我想创建一个如下图: Correct Graph

这是我当前的ggplot2代码:

library(ggplot2)    
ggplot(df,aes(factor(year,levels=c('2013','2012','2011')),pct,fill=ind)) +
geom_bar(stat="identity",position="stack") +
geom_text(aes(label=ifelse(ind=="1",
                  paste0("YES\n",format(n,big.mark=","), " (",sprintf("%.0f", pct*100),"%)"),
                  paste0("NO\n", format(n,big.mark=","), " (",sprintf("%.0f", pct*100),"%)"))
                  ),
           position=position_dodge(width=1)) + 
theme(axis.title=element_blank(),
axis.ticks=element_blank(),
axis.text.x =element_blank(),
panel.grid=element_blank(),
panel.background = element_blank(),
legend.position="none") +
facet_grid(.~factor(type,levels=c('A','B')), scale='free') + 
coord_flip()

我当前拥有的代码输出以下图形: Incorrect Graph

我的问题是,如何固定标签,使其像第一个图形一样显示?

1 个答案:

答案 0 :(得分:0)

如果我这样添加y = 0.5

year <- c(2011,2012,2012,2013,2013,2011,2011,2012,2012,2013,2013)
type <- c('A','A','A','A','A','B','B','B','B','B','B')
ind <- c(1,0,1,0,1,0,1,0,1,0,1)
n <- c(9000,5,9000,5,9000,10,10000,10,10000,10,10000)
pct<-c(1,0.01,0.99,0.01,0.99,0.01,0.99,0.01,0.99,0.01,0.99)
df <- data.frame(year, type, ind, n, pct)
df$ind <- as.factor(df$ind)

library(ggplot2)    
ggplot(df,aes(factor(year,levels=c('2013','2012','2011')),pct,fill=ind)) +
  geom_col() +
  geom_text(aes(label=ind, y=0.5), position=position_dodge(width=1)) + 
  facet_grid(.~factor(type,levels=c('A','B')), scale='free') + 
  coord_flip() 

它给了我这样的情节:

enter image description here