My data consists of a date variable and four numeric variables, of the 4 numeric variables I wish to plot two of these as a stacked bar chart and the remaining variables as line charts.
Is it possible to create two line charts and a stacked bar chart in a single plot using ggplot?
My data looks as follows:
data <- tibble(Month = 1:12,Brands = c(1,1,1,1,1,1,2,2,2,2,2,2),Generics = Brands 1,Metric1 = c(5,5,5,5,5,5,6,6,7,8,9,10),Metric2 = c(10,10,11,11,12,13,14,15,16,17,18,19))
I wish to plot months on the x axis, Brands1 & Brands2 as stacked bar charts and Metric1 & Metric2 as line charts all on the same chart if possible.
CodePudding user response:
Something like this?
library(tidyverse)
data <- tibble(Month = 1:12,Brands = c(1,1,1,1,1,1,2,2,2,2,2,2),Generics = Brands 1,Metric1 = c(5,5,5,5,5,5,6,6,7,8,9,10),Metric2 = c(10,10,11,11,12,13,14,15,16,17,18,19))
data %>%
pivot_longer(cols = c(Brands,Generics)) %>%
pivot_longer(cols = c(Metric1,Metric2),
names_to = "metric_name",values_to = "metric_value") %>%
ggplot(aes(Month))
geom_col(aes(y = value, fill = name))
geom_line(aes(y = metric_value, col = metric_name),size = 1.25)
scale_x_continuous(breaks = 1:12)
scale_color_manual(values = c("black","purple"))