R ggplot:动态对齐geom_text标签

时间:2019-01-06 23:58:09

标签: r ggplot2 bar-chart

我制作了一个漏斗图,以显示各个阶段的转化 A> B> C> D

下面是R代码:

library(ggplot2)
library(ggthemes)
options(scipen = 999)  # turns of scientific notations like 1e+40

stage <- c("A","A", "B","B","C","C","D","D")
percent <- c(-100,100,-75,75,-50,50,-10,10)
funnel_df <- data.frame(stage, percent)

# X Axis Breaks and Labels 
brks <- seq(-100, 100, 10)
lbls = paste0(as.character(seq(0, 100, 5), "%"))

# Plot
ggplot(funnel_df, aes(x = stage, y = percent)) +   # Fill column
  geom_bar(stat = "identity", width = .6) +   # draw the bars
  geom_text(data=funnel_df, 
            aes(label= paste(round(percent), '%'), hjust = c(4,4,4,4,4,4,4,1)),
            color='white') +
  scale_y_continuous(breaks = brks,   # Breaks
                     labels = lbls) + # Labels
  coord_flip() +  # Flip axes
  labs(title="Email Campaign Funnel") +
  theme_tufte() +  # Tufte theme from ggfortify
  theme(plot.title = element_text(hjust = .5), 
        axis.ticks = element_blank()) +   # Centre plot title
  scale_fill_brewer(palette = "Dark2")  # Color palette

以下是我得到的输出: enter image description here

该图正确显示。但是,我希望条形图上的文本标签始终位于条形图的中心。我知道我可以使用 just 参数移动标签。但是,就我而言,阶段A将始终为100%,但阶段B,C和D将动态变化。因此,我无法对 just 参数中的值进行硬编码。有没有一种方法可以使文本标签动态居中对齐?

1 个答案:

答案 0 :(得分:3)

图的中心始终位于y = 0(y,因为您已经翻转了坐标)。因此,您可以通过将y值设置为0来使文本居中,如

ggplot(funnel_df, aes(x = stage, y = percent)) +   # Fill column
  geom_bar(stat = "identity", width = .6) +   # draw the bars
  geom_text(data=funnel_df[1:nrow(funnel_df) %% 2 == 0, ], # only want to positive percents
            aes(y = 0, label= paste(round(percent), '%')), # y = 0 is centered
            color='white') +
  scale_y_continuous(breaks = brks,   # Breaks
                     labels = lbls) + # Labels
  coord_flip() +  # Flip axes
  labs(title="Email Campaign Funnel") +
  theme_tufte() +  # Tufte theme from ggfortify
  theme(plot.title = element_text(hjust = .5), 
        axis.ticks = element_blank()) +   # Centre plot title
  scale_fill_brewer(palette = "Dark2")  # Color palette

产生:

Percents are centered automatically, regardless of bar width (as long as bars are centered on 0)