标签在堆叠条形图ggplot2上重叠 [英] Labels overlapping on Stacked bar chart ggplot2

查看:76
本文介绍了标签在堆叠条形图ggplot2上重叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码生成适当堆叠的条形图.但是,我试图添加标签以显示每个填充位置中的百分比.在下面的代码中,百分比标签不与填充边界对齐,并且所有堆栈"都在0点附近.

The code below generates an appropriately stacked bar chart. However, I am trying to add labels to show the percentage in each fill location. With the code below, the percentage labels do not align with the fill boundaries and all "stack" near the 0 point.

这是我使用的代码

pff <- read.table(header=TRUE, text='REGION Q99
Tunis NidaaTounes
Tunis Nepasvoter
Tunis Nahdha
Tunis Nepasvoter
Tunis Nahdha
Tunis Nahdha
Tunis NidaaTounes
Tunis Jabha
Tunis NidaaTounes
Tunis Autres
Tunis Nahdha
Tunis Nahdha
Tunis Autres
Tunis Jabha
Tunis Nepasvoter
Tunis Nepasvoter
Tunis CPR
Tunis Nahdha
Tunis Nepasvoter
Tunis Nepasvoter
Ariana Nahdha
Ariana Nepasvoter
Ariana NidaaTounes
Ariana CPR
Ariana NidaaTounes
Ariana NidaaTounes
Ariana NidaaTounes
Ariana CPR
Ariana Nahdha', stringsAsFactors=FALSE)

g <- ggplot(pff, aes(x = REGION, y =(..count..)/sum(..count..), fill=Q99))
g <- g + geom_bar(position="stack") + 
  labs(title="Vote par région") +
  labs(x=" ", y=" ")+
  labs(fill="Parti Politique")+
  coord_flip()+
  # scale_fill_manual(values=cbPalette)+
  scale_y_continuous(labels = percent)+
  theme_bw()+
  theme(panel.border = element_rect(colour = "white")) + 
  geom_text(aes( label = scales::percent((..count..)/sum(..count..)),
                 y=(..count..)/sum(..count..)), stat= "count", size=3)

推荐答案

我意识到这确实很老,但是您要寻找的解决方案是添加 position = position_stack(vjust = 0.5)到您的 geom_text()调用中.像这样:

I realize this is really old, but the solution you're looking for is to add position = position_stack(vjust = 0.5) to your geom_text() call. Like so:


g <- ggplot(pff, aes(x = REGION, y =(..count..)/sum(..count..), fill=Q99))
g <- g + geom_bar(position="stack") + 
  labs(title="Vote par région") +
  labs(x=" ", y=" ")+
  labs(fill="Parti Politique")+
  coord_flip()+
  # scale_fill_manual(values=cbPalette)+
  scale_y_continuous(labels = percent)+
  theme_bw()+
  theme(panel.border = element_rect(colour = "white")) + 
  geom_text(aes( label = scales::percent((..count..)/sum(..count..)),
                 y=(..count..)/sum(..count..)), stat= "count", size=3, position = position_stack(vjust = 0.5))

这篇关于标签在堆叠条形图ggplot2上重叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆