Сумма на столбик с накоплением
Если вы хотите добавить сумму на столбец, я предлагаю вам вычислить ее заранее, а затем запросить.
# This calculates the totals per category
tots = df %>%
group_by(region, product) %>%
summarise(total=sum(price))
# This plots the results
df %>%
ggplot(aes(product, y = price, fill = delivery)) +
geom_col(position = "stack") +
facet_grid(.~region, switch = "x") +
geom_text(aes(product, total, fill= NULL, label = total), data=tots, size = 3, hjust = 0.5, vjust = 3, position = "stack")
geom_text
использует фрейм данных tots
, который содержит итоговые значения для запроса.
Результат следующий:
Adding subtotal per delivery
No big difference, you just have to add a subtotal df and prompt both:
tots = df %>%
group_by(region, product) %>%
summarise(total=sum(price))
stots = df %>%
group_by(region, product, delivery) %>%
summarise(stotal=sum(price)) %>%
arrange(desc(delivery))
df %>%
ggplot(aes(product, y = price, fill = delivery)) +
geom_col(position = "stack") +
facet_grid(.~region, switch = "x") +
geom_text(aes(product, stotal, fill= NULL, label = stotal), data=stots, size = 3, hjust = 0.5, vjust = 3, position = "stack") +
geom_text(aes(product, total, fill= NULL, label = total, fontface=2), data=tots, size = 4, hjust = 0.5, vjust = -0.5, position = "stack")
Я сделал это (и изменил шрифт на 2, чтобы общее число было жирным)
Adding the cumulative sum per delivery inside
Pretty much the same trick, but aggregating the tots
data before.
I did it by doing arrange
and mutate
on top of summarise
, and precising delivery in the group_by
.
tots2 = df %>%
group_by(region, product, delivery) %>%
summarise(total=sum(price)) %>%
arrange(desc(delivery)) %>%
mutate(cumtot=cumsum(total))
df %>%
ggplot(aes(product, y = price, fill = delivery)) +
geom_col(position = "stack") +
facet_grid(.~region, switch = "x") +
geom_text(aes(product, total, fill= NULL, label = cumtot), data=tots2, size = 3, hjust = 0.5, vjust = 3, position = "stack")
Output:
Cumulative sum
I calculated the cumulated price before plotting it like this:
df %>%
group_by(region, product) %>%
arrange(desc(delivery)) %>%
mutate(cum_price = cumsum(price)) %>%
ggplot(aes(product, y = price, fill = delivery)) +
geom_col(position = "stack") +
facet_grid(.~region, switch = "x") +
geom_text(aes(label = cum_price), size = 3, hjust = 0.5, vjust = 3, position = "stack")
The arrange
is added to ensure your sum is cumulated in the same order as your plot.
Result is the following:
введите описание изображения здесь