I have a dataset containing y variable as Year and x variables as (A, B, C(%)). I have attached the dataset 
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:
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)



