是否有可能在 ggplot2 的堆积条形图中组合 position_stack 和 nudge_x?

Is there a possibility to combine position_stack and nudge_x in a stacked bar chart in ggplot2?

我想向堆积条形图添加标签以实现如下目的:

目标很简单:我需要在同一张图表中显示市场份额和与上一年相比的变化。理论上,我会在代码中将 "nudge_x=0.5," 添加到 geom_text,但出现错误:"Specify either position or nudge_x/nudge_y"。是否可以使用一些解决方法,也许是另一个包?提前致谢!

代码:

        DashboardCategoryText <- c("Total Market","Small Bites","Bars","Total Market","Small Bites","Bars","Total Market","Small Bites","Bars")
    Manufacturer <- c("Ferrero","Ferrero","Ferrero","Rest","Rest","Rest","Kraft","Kraft","Kraft")
    MAT <- c(-1,5,-7,6,8,10,-10,5,8)
    Measure_MATCurrent <- c(500,700,200,1000,600,80,30,60,100)

    data <- data.frame(DashboardCategoryText,Manufacturer,MAT,Measure_MATCurrent)

    library(dplyr)
    groupedresult <- group_by(data,DashboardCategoryText)
    groupedresult <- summarize(groupedresult,SUM=sum(Measure_MATCurrent))
    groupedresult <- as.data.frame(groupedresult)

    data <- merge(data,groupedresult,by="DashboardCategoryText")

    data$percent <- data$Measure_MATCurrent/data$SUM

    library(ggplot2)

    ggplot(data, aes(x=reorder(DashboardCategoryText, SUM), y=percent, fill=Manufacturer)) +
          geom_bar(stat = "identity", width = .7, colour="black", lwd=0.1) +
          geom_text(aes(label=ifelse(percent >= 0.005, paste0(sprintf("%.0f", percent*100),"%"),"")),
          position=position_stack(vjust=0.5), colour="white") +
          geom_text(aes(label=MAT,y=percent),
          nudge_x=0.5,
          position=position_stack(vjust=0.8),
          colour="black") +
          coord_flip() +
          scale_y_continuous(labels = percent_format()) +
          labs(y="", x="")

我有一个有点 'hacky' 的解决方案,您基本上只需在绘制它之前更改基础 ggplot 对象中的 geom_text 数据。

p <- ggplot(data, aes(x=reorder(DashboardCategoryText, SUM), y=percent, fill=Manufacturer)) +
    geom_bar(stat = "identity", width = .7, colour="black", lwd=0.1) +
    geom_text(aes(label=ifelse(percent >= 0.005, paste0(sprintf("%.0f", percent*100),"%"),"")),
              position=position_stack(vjust=0.5), colour="white") +
    geom_text(aes(label=MAT,y=percent),
              position=position_stack(vjust=.5),
              colour="black") +
    coord_flip() +
    scale_y_continuous(labels = percent_format()) +
    labs(y="", x="")

q <- ggplot_build(p)  # get the ggplot data
q$data[[3]]$x <- q$data[[3]]$x + 0.5  # change it to adjust the x position of geom_text
plot(ggplot_gtable(q))  # plot everything