首页 > 解决方案 > 如何在 R (ggplot2) 中创建多个变量的堆积柱图

问题描述

目前,我有一个如下所示的数据框:

Month   Total Revenue    Dues   Total Retail    Other Revenue
8/31/2020   36615.00     30825  1200            4590
9/30/2020   38096.69     34322  2779.4          995.29
10/31/2020  43594.15     35936  2074.68         5583.47
11/30/2020  51856.9      43432  993.5           7431.4

我想在 ggplot 中创建一个图(我想应该是一个堆叠的列),按类型显示每个月的收入组合。对于我的数据,总收入是会费、零售总额和其他收入的总和。会费、总零售收入和其他收入应该相互叠加,每一个都有自己的颜色。我还想要柱形图上的标签,描述每种收入来源占总收入的百分比。

我可以毫无问题地绘制总收入,但我似乎无法将这些列拆分开来。到目前为止,我唯一成功的例子如下。

# Create Column Plot of Total Revenue
library(tidyverse)
plot1 <- ggplot(August_Data, aes(Month_End, `Total Revenue`)) + geom_col()

这个例子显然没有将收入分成正确的子类别。我认为使用填充命令可能会起作用,但是我遇到了错误。

plot1 <- ggplot(August_Data, aes(Month_End, `Total Revenue`)) + geom_col(aes(fill = C(Dues, `Total Retail`, `Other Revenue`)))

非常感谢你的帮助

标签: rggplot2data-visualization

解决方案


澄清后更新:

library(tidyverse)
library(lubridate)
df %>% 
    mutate(Month = mdy(Month)) %>% # this line is not necessary in OPs original code (not the one presented here)
    pivot_longer(
        cols = c("Dues", "TotalRetail", "OtherRevenue"),
        # cols = -c(Month_End, SID) in OPs original code
        names_to = "names", 
        values_to = "values"
    ) %>% 
    mutate(percent = values/TotalRevenue*100) %>% 
    ggplot(aes(x = Month, y= values, fill= names))+
    geom_col() +
    geom_text(aes(label = paste0(round(percent,1),"%")), 
              position = position_stack(vjust = 0.5), size = 5)

在此处输入图像描述

第一个答案: 你快到了。旋转更长的时间并添加fill.

library(tidyverse)
library(lubridate)

df %>% 
    mutate(Month = mdy(Month)) %>% 
    pivot_longer(
        -Month, 
        names_to = "names", 
        values_to = "values"
    ) %>% 
    ggplot(aes(x = Month, y= values, fill= names))+
    geom_col()
    

在此处输入图像描述


推荐阅读