r - 如何在 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`)))
非常感谢你的帮助
解决方案
澄清后更新:
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()
推荐阅读
- matlab - 在 Matlab 中并行执行 COM 实例
- python - python - 如何使用TFIDF为python中的每一行提取关键字?
- python - 如何显示由 pandas read_csv() 函数读取的 csv 文件名?
- java - ObjectMapper 反序列化设置所有字段 = NULL
- angular - ion-infinite-scroll 不触发 ionInfinite 事件 - Ionic 5
- c# - 从 Visual Studio 运行时查看最终控制台输出,无需 ReadLine()
- html - 在不强制高度的情况下填充剩余空间
- vb.net - 删除文件,即使它正在运行
- json - 在 SQL Server 中读取和写入 JSON
- php - 应用了自定义 CSS 的 Word 到 PHP