我也尝试过同样的情况geom_col()
以及,但我也遇到了同样的问题 - 与position = "stack"
看来我们不能分配width
参数无需拆栈。
但事实证明,这个解决方案非常简单——我们可以使用geom_rect()
“手工”构建这样的情节。
有你的数据:
df <- data.frame(
procedure = rep(paste("method", 1:4), times = 3),
sector = rep(c("construction", "delivery", "service"), each = 4),
amount = c(100, 20, 10, 80, 75, 80, 50, 20, 20, 25, 10, 4),
amount_mean = c(1, 1.2, 0.2, 0.5, 1.3, 0.8, 1.5, 1, 0.8, 0.6, 0.2, 0.9)
)
首先我转换了你的数据集:
df <- df |>
mutate(
amount_mean = amount_mean / max(amount_mean),
sector_num = as.numeric(sector)
) |>
arrange(desc(amount_mean)) |>
group_by(sector) |>
mutate(
xmin = sector_num - amount_mean / 2,
xmax = sector_num + amount_mean / 2,
ymin = cumsum(lag(amount, default = 0)),
ymax = cumsum(amount)
) |>
ungroup()
我在这里做什么:
- 我缩小了规模
amount_mean
, 所以0 >= amount_mean <= 1
(更适合绘图,无论如何我们没有另一个比例来显示真实值amount_mean
);
- 我也解码了
sector
变量转换为数值(用于绘图,见下文);
- 我已按降序排列数据集
amount_mean
(沉重的手段- 在底部,光的意思是在顶端);
- 按部门分组,我计算了
xmin
, xmax
来代表amount_mean
, and ymin
, ymax
对于金额。前两者有点棘手。ymax
很明显 - 你只需采取累计总和对全部amount
从第一个开始。你需要累计总和计算ymin
也一样,但是从0开始。所以第一个矩形绘制为ymin = 0
, 第二个 - 与ymin = ymax
前一个三角形等。所有这些都是在每个单独的组中执行的sector
s.
绘制数据:
df |>
ggplot(aes(xmin = xmin, xmax = xmax,
ymin = ymin, ymax = ymax,
fill = procedure
)
) +
geom_rect() +
scale_x_continuous(breaks = df$sector_num, labels = df$sector) +
#ggthemes::theme_tufte() +
theme_bw() +
labs(title = "Question 51136471", x = "Sector", y = "Amount") +
theme(
axis.ticks.x = element_blank()
)
Result:
防止的另一种选择procedure
要重新排序的变量。所以都说“红色”在下面,“绿色”在上面等等。但它看起来很丑:
df <- df |>
mutate(
amount_mean = amount_mean / max(amount_mean),
sector_num = as.numeric(sector)
) |>
arrange(procedure, desc(amount), desc(amount_mean)) |>
group_by(sector) |>
mutate(
xmin = sector_num - amount_mean / 2,
xmax = sector_num + amount_mean / 2,
ymin = cumsum(lag(amount, default = 0)),
ymax = cumsum(amount)
) |>
ungroup()