R 中多列整数的堆积条形图

问题描述

为我假设的事情寻求帮助是一项非常简单的任务。根据我下面的数据,我想创建一个带有 fill = colnames(df_Consumers)[2,4] 的堆积条形图。我试图让 x 轴为 df_Consumers$Month,y 轴为 df_Consumers$Referrals,第 2 列和第 4 列是堆积条形图。我希望这是有道理的。如果我太含糊,请提前道歉。我的 ggplot 代码和数据如下。提前致谢!

ggplot(df_Consumers,aes(x = Month,y = Referrals)) +
  geom_col(aes(fill = df_Consumers[2,4]))

enter image description here

解决方法

ggplot 喜欢长数据帧。我建议如下:

library(tidyverse)

df_Consumers %>%
  select(-Referrals) %>%
  pivot_longer(c(New.Consumers,No.Fill),names_to = "type",values_to = "value") %>%
  ggplot() + 
  aes(x = Month,y = value,fill = type) + 
  geom_col()