Reputation: 670
I want to create a stacked barchart but I'm struggling to get i right. I want to add the green and red bar on top (i.e. in front) of the blue bar. The blue bar represents some total; hence, the red and green bar is only a proportion of that value. Any is ideas how I can do this?
Here's is my code:
sse <- c(3243.784, 2527.5, 716.3)
model <- c('sst', 'ssm', 'ssr')
bar <- tibble(sse, model)
ggplot(bar, aes(x = model, y = sse, fill = model)) +
geom_col()
Upvotes: 0
Views: 1892
Reputation: 23807
Just use a placeholder as x. BTW, this method is also what is used when you're creating pie charts from bar graphs.
library(tidyverse)
sse <- c(3243.784, 2527.5, 716.3)
model <- c('sst', 'ssm', 'ssr')
foo <- tibble(sse, model)
ggplot(foo, aes(x = "", y = sse, fill = model)) +
geom_col()
Created on 2021-05-16 by the reprex package (v2.0.0)
Upvotes: 2
Reputation: 36
Since the blue bar represents the total value (i.e. sum of red and green bars), I think you can show only red and green while showing data values on stacked bar plots. In this way, there will not be any confusion and you can show the values of "ssm", "ssr", and "sst" at the same time.
Here is the code that you may use:
library(tibble)
library(ggplot2)
sse <- c(2527.5, 716.3)
model <- c('ssm', 'ssr')
value <- c('sst')
bar <- tibble(sse, model, value)
ggplot(bar, aes(x = value, y = sse, fill = sse, label = sse)) +
geom_bar(position = "stack", stat = "identity", width = .3) +
geom_text(size = 3, position = position_stack(vjust = 0.5))
I added a new variable titled value which represents the "sst".
Also, I used geom_bar instead of geom_col because it would be better for the visualization.
Lastly, I used geom_text to add data values to the stacked bars.
Here is how it should look like:
Upvotes: 2