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

标签 r ggplot2 geom-bar stacked

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

enter image description here

目标很简单:我需要在同一图表中显示与上一年相比的市场份额和变化。理论上,我只会在代码中的 geom_text 中添加“nudge_x=0.5”,但出现错误:“指定 positionnudge_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”的解决方案,您基本上只需更改 geom_text底层数据ggplot在绘制对象之前。

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

plot

关于r - 是否有可能在 ggplot2 的堆积条形图中组合 position_stack 和 nudge_x?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57525176/

相关文章:

R Plumber 发布 PDF

R 根据排列更改 data.table 中列值的顺序

r - 如何使用 data.table 执行 "setdiff"合并?

r - 设置带有端点的 ggplot 网格线/ggplot 的中断计算

r - 使用 ggplot2 以粗体突出显示单个轴标签

r - 您可以在 R 中将 geom_bar 饼图与 geom_point 图结合起来吗?

r - 使用 ggplot2 笔画控制条边框(颜色)厚度

r - 如何使用 geom_bar() 在 R 中创建两个分组列

删除 ggplot2 中多余的图例

r - ggplot 不绘制箱线图