Yolo_chicken
Yolo_chicken

Reputation: 1391

ggplot Find sum of all groups and plot as line

I have a data that looks like this

Group   x    y
 A      2    30
 B      2    21
 C      2    22
 A      3    15
 B      3    18
 C      3    5   
 A      4    14
 B      4    29
 C      4    46 

And create a chart with:

gg <- ggplot(mydata,
         aes(x=x, y=y, fill=Group, group=Group))+
      geom_line(data =mydata,
        aes(x=x, y=y,colour=Group),
        stat="identity",
        size=1.5)
plot(gg)

I'm trying to add a fourth line that has the sum of A+B+C at every X. I've tried this but it adds 5 lines, not one with a sum. I want a line that would be y=73 when x=2, y=38 when x=3, and y=89 when x=4.

Code:

Group <- c("A", "B", "C","A", "B", "C","A", "B", "C")
x <- c(2,2,2,3,3,3,4,4,4)
y <- c(30,21,22,15,18,5,14,29,46) 
mydata <- data.frame(Group,x,y)



gg <- ggplot(mydata,
         aes(x=x, y=y, fill=Group, group=Group))+
      geom_line(data =mydata,
        aes(x=x, y=y,colour=Group),
        stat="identity",
        size=1.5)
plot(gg)

Upvotes: 0

Views: 2686

Answers (1)

tifu
tifu

Reputation: 1411

One way would be to generate a variable that sums all values of y by x via dplyr's group_by and mutate-functions. You can then generate your plot and add a second line geom that will show the x-specific sums.

library(tidyverse)    

mydata %>%
  group_by(x) %>%
  mutate(sum.y = sum(y)) %>%
ggplot(aes(x=x, y=y, color=Group))+
  geom_line(size=1.5) +
  geom_line(aes(y = sum.y), color = "black") 

Note that I changed your code by removing redundant code in the aesthetics, stat = "identity" in geom_line and all of the data = mydata specifications. These are simply not necessary.

enter image description here

Upvotes: 1

Related Questions