Home > Back-end >  How to implement stacked bar graph with a line chart in R
How to implement stacked bar graph with a line chart in R

Time:06-10

I have a dataset containing y variable as Year and x variables as (A, B, C(%)). I have attached the dataset enter image description here

The variables A and B will be plotted as stacked bar graph and the C will be plotted as line chart in the same plot. I have generated the plot using excel like below:

enter image description here

How can I create the same plot in R?

CodePudding user response:

You first need to reshape longer, for example with pivot_longer() from tidyr, and then you can use ggplot2 to plot the bars and the line in two separate layers. The fill = argument in the geom_bar(aes()) lets you stratify each bar according to a categorical variable - name is created automatically by pivot_longer().

library(ggplot2)
library(tidyr)

dat |> 
  pivot_longer(A:B) |> 
  ggplot(aes(x = Year))  
  geom_bar(stat = "identity", aes(y = value, fill = name))  
  geom_line(aes(y = `C(%)`), size = 2)

Created on 2022-06-09 by the enter image description here

  • Related