【问题标题】:Is there a possibility to combine position_stack and nudge_x in a stacked bar chart in ggplot2?是否有可能在 ggplot2 的堆积条形图中组合 position_stack 和 nudge_x ?
【发布时间】:2019-08-16 13:03:16
【问题描述】:

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

目标很简单:我需要在同一张图表中显示市场份额和与上一年相比的变化。理论上,我只需在代码中的 geom_text 中添加“nudge_x=0.5”,但出现错误:“指定position 或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="")

【问题讨论】:

标签: r ggplot2 geom-bar stacked


【解决方案1】:

我有一个有点“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

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2017-08-04
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    相关资源
    最近更新 更多