mbrandalero
mbrandalero

Reputation: 416

Continuous outline in stacked ggplot2 barplot

Say I have a data frame df that looks like this.

Year   value     type
2000    150    Type 1
2000    200    Type 1
2000     70    Type 2
2000     20    Type 1
2005     50    Type 2
2005     80    Type 2
2005     50    Type 1
2005     50    Type 1

I want to plot the total of value per Year, regardless of the type. With ggplot, I can do

ggplot(df) +
    geom_col(aes(x = x, y = y),
             colour = "black", fill = "dodgerblue2")

which yields the following plot:

Plot example

This plot shows a separation between each observation (black lines separating the boxes, due to the /color/ argument), which is undesired if I'm interested only in the total.

Is there some way I can draw the outline of the entire bar for each year, ignoring the individual observations?

What I wish to achieve is something like this:

enter image description here

P.s.1: code to generate the data frame for the MWE

df <- data.frame(
    year = as.factor(c(2000, 2000, 2000, 2000, 2005, 2005, 2005, 2005)),
    value = c(150, 200, 70, 20, 50, 80, 50, 50),
    type = as.factor(c("Type 1", "Type 1", "Type 2", "Type 1",
                       "Type 2", "Type 2", "Type 1", "Type 1")))

P.s.2: I know I can achieve the desired effect by creating a new data frame with the total count for the variable value per year. I'm interested if there's a direct solution with ggplot2 which doesn't require me to create a new data frame.

Upvotes: 2

Views: 1393

Answers (1)

Jack Brookes
Jack Brookes

Reputation: 3830

You can use stat_summary with function sum() and geom of col.

library(ggplot2)
library(dplyr)

df <- data.frame(
  year = as.factor(c(2000, 2000, 2000, 2000, 2005, 2005, 2005, 2005)),
  value = c(150, 200, 70, 20, 50, 80, 50, 50),
  type = as.factor(c("Type 1", "Type 1", "Type 2", "Type 1",
                     "Type 2", "Type 2", "Type 1", "Type 1")))

ggplot(df) +
  stat_summary(aes(x = year, y = value),
               fun.y = sum,
               geom = "col",
               colour = "black",
               fill = "dodgerblue2")

enter image description here

Upvotes: 5

Related Questions