rggplot2bar-chartstacked-bar-chart

How to build a stacked barchart with two continuous columns in ggplot


I would like to create an horizontal rancked stacked barchart. The bars should show the sum of "cost1" and "cost2" with one labels at the end of each bar . Below, you can see the code but I am stack with it beceause it is not rancked and the label numbers do not work. I used the pivot_longer function but maybe it is not the correct way to rearrange the dataset. I am sure there is an easy and clear way to do it. Could you please help me?

library(tidyverse)

data_test <- tribble(
  ~name, ~cost1, ~cost2, ~totalCost,
  "John", 10, 40, 50,
  "Martin", 21, 35, 56,
  "Michael", 15, 80, 95,
  "Dave", 28, 40, 68,
  "Dan", 18, 35, 53
)
View(data_test)

df <- data_test %>%
  pivot_longer(cols = c("cost1", "cost2"),
               names_to = "cost",
               values_to = "value")

ggplot(df, aes(x=name, y=value, fill = cost)) +
  geom_bar(position = "fill", stat = "identity") +
  coord_flip()

enter image description here


Solution

  • I think you're looking for this:

    ggplot(df, aes(y=name, x=value, fill = cost)) +
      coord_cartesian(clip = "off") +
      geom_bar(position = "stack", stat = "identity") +
      geom_text(
        aes(label = after_stat(x), group = name), 
        stat = 'summary', fun = sum, hjust = -0.5
      )
    

    enter image description here