【问题标题】:Labels overlapping on Stacked bar chart ggplot2标签在堆叠条形图ggplot2上重叠
【发布时间】:2016-09-01 11:06:37
【问题描述】:

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

这是我使用的代码

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 = "stack" 添加到geom_text 呼叫。现在位置都是从0开始的;你需要他们建立在彼此之上。如果问题被解锁,我将发布作为答案。 @zx8754 和 @Procastinatus Maximus
  • 非常感谢@MarkPeterson,它可以工作,但在位置 =“fill”的情况下,我收到此错误错误:position_fill 需要以下缺失的美学:ymax
  • 除了position = "stack"(在this question 中很好地显示),在ggplot2 之外计算标签和y 位置以使事情看起来更好是相当普遍的。有很多例子,包括一个基本的 herehere

标签: r ggplot2


【解决方案1】:

我意识到这确实很旧,但您正在寻找的解决方案是将position = position_stack(vjust = 0.5) 添加到您的geom_text() 电话中。像这样:


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))

【讨论】:

    猜你喜欢
    • 2012-01-04
    • 1970-01-01
    • 2018-09-30
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 2014-08-30
    • 2019-07-19
    • 1970-01-01
    相关资源
    最近更新 更多