【问题标题】:R ggplot: Dynamic align geom_text labelsR ggplot:动态对齐geom_text标签
【发布时间】:2019-01-06 23:58:09
【问题描述】:

我制作了一个漏斗图来显示各个阶段的转化率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

以下是我得到的输出:

情节显示正确。但是,我希望条形图上的文本标签始终位于条形图的中心。我知道我可以使用 hjust 参数来移动标签。但是,在我的例子中,阶段 A 将始终为 100%,但阶段 B、C 和 D 将动态变化。所以我不能硬编码 hjust 参数中的值。有没有办法可以动态居中对齐文本标签?

【问题讨论】:

    标签: r ggplot2 bar-chart


    【解决方案1】:

    绘图的中心始终位于 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
    

    生产:

    【讨论】:

      猜你喜欢
      • 2022-11-25
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2018-11-02
      • 2018-01-08
      • 1970-01-01
      • 2019-08-11
      • 1970-01-01
      相关资源
      最近更新 更多