【发布时间】:2019-09-06 10:16:29
【问题描述】:
最近我在做一个项目时遇到了一个问题。简而言之,我需要为 2 个不同的指标绘制 100% 堆积条形图,分别是 网点数量(客户)和 这些网点的销售额 3 个分类。因此,我需要使用 2 个 y 轴来分别说明这两个。但是,我想显示数据标签的绝对值而不是相对百分比。而且问题很明显,因为这两个指标的值在不同的范围内,导致标签放置在错误的位置。
- 我使用 facet_wrap 将两个指标分成 2 个方面进行说明。
- 通过使用 position = "fill",我可以显示绝对值而不是计算定量(介于 0 和 1 之间)。
- 使用 position = position_stack(vjust = 0.5) 使我能够将数据标签对齐到条形图的中心。但是,它仅适用于 1 个指标。
dt_4_slide1_long_test %>%
ggplot(aes(x = month, y = value, fill = OutletClassification, label = value))+
geom_bar(position = "fill",stat = "identity")+
facet_wrap(~variable)+
ggtitle("Sales and Outlet Proportion by Channel")+
geom_text(aes(
x = month,
y = ave(value, month, FUN = function(x) (cumsum(x) - 0.5 * x) / sum(x)),
label = value
),
position = position_stack(vjust = 0.5),
size = 2
)+
theme(plot.title = element_text(size = 16, hjust = 0.5, vjust = 1),
legend.text = element_text(size=8),
legend.position = "bottom")
所以,我的期望是我可以显示与条形图中心对齐的 2 个指标的绝对值。
这是示例数据 Sample data
或者这个示例数据可能会有所帮助:
structure(list(month = c("2019-06", "2019-07", "2019-08", "2019-06",
"2019-07", "2019-08", "2019-06", "2019-07", "2019-08", "2019-06",
"2019-07", "2019-08", "2019-06", "2019-07", "2019-08", "2019-06",
"2019-07", "2019-08"), OutletClassification = c("0010102_Lẻ đường phố",
"0010102_Lẻ đường phố", "0010102_Lẻ đường phố",
"0010401_Chạp phô", "0010401_Chạp phô", "0010401_Chạp phô",
"0010402_Lẻ chợ", "0010402_Lẻ chợ", "0010402_Lẻ chợ",
"0010102_Lẻ đường phố", "0010102_Lẻ đường phố",
"0010102_Lẻ đường phố", "0010401_Chạp phô", "0010401_Chạp phô",
"0010401_Chạp phô", "0010402_Lẻ chợ", "0010402_Lẻ chợ",
"0010402_Lẻ chợ"), variable = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("no_customer",
"total_sales"), class = "factor"), value = c(29, 30, 26, 18,
16, 15, 109, 109, 101, 234.062, 248.07, 195.67, 34.415, 28.077,
36.29, 618.741, 543.843, 474.76)), row.names = c(NA, -18L), class = "data.frame")
【问题讨论】:
-
请以简单、可重复的格式提供您的数据(例如使用
dput())。 -
是的,我使用了 dput() 并且已经在问题中输入了数据
标签: r ggplot2 bar-chart data-visualization