3

I have been trying to plot clustered columns with running totals in. I have two types of columns and just need R to calculate the running total of each them separately. For some reason it's adding running totals of different types together.

library(ggplot2)
df = data.frame(date = c(1, 1, 2, 2, 3, 3),
                val  = c(5, 2, 5, 2, 5, 2),
                type = c("honey","bread","honey","bread","honey","bread"))

ggplot(df, aes(x=date, y=cumsum(val), group = type, fill=type)) +
geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + theme_classic()

I am getting:

I am getting

What I am looking is to have a running total in, showing honey with values of 5,10 and 15, and bread with values of 2, 4 and 6.

enter image description here

What am I doing wrong? Any idea?

3 Answers 3

3

You can try something like this:

library(ggplot2)
library(dplyr)

df1 <- df %>% group_by(type) %>% mutate(N=cumsum(val))

ggplot(df1,aes(x=date, y=N, group = type, fill=type)) +
  geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + theme_classic()

Which gives:

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

enter image description here Another solution

ggplot(df, aes(x=date, y=ave(x = val, type, FUN = cumsum), group = type, fill=type)) +
  geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + theme_classic()

Comments

1

I would rather do the calculation within ggplot, but outside to caluclate the cumsum().

Here is my suggestion:

library(ggplot2)
library(dplyr)

df %>% 
  group_by(type) %>% 
  mutate(total = cumsum(val)) %>% 
  ggplot(aes(x = date, y = total, fill = type)) +
  geom_bar(position = position_dodge(preserve = 'total'), stat="identity") + 
  theme_classic()

... which gives you that output:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.