Home > front end >  overlayed ggplot with barchart and line graph
overlayed ggplot with barchart and line graph

Time:09-13

I have a dataframe which is showing gas and electricity usage, and an associated price, over a range of dates. I'm trying to plot the usage (of both gas and electricity) as a bar chart (where the bar is coloured proportionally for the usage of each utility), and and 2 overlayed lines indicating the price of gas and electricity over the same time periods. This is a snippet of the data frame, named 'cost'. Any ideas people have would be greately appreciated.

structure(list(Date = structure(c(18686, 18686, 18714, 18714, 
18745, 18745), class = "Date"), Utility = c("Gas", "Electricity", 
"Gas", "Electricity", "Gas", "Electricity"), usage = c(0, 0, 
125, 208, 104, 232), price = c(0, 0, 45.46, 37.82, 39.67, 43.09
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

I have managed to render the plots separately, but can not seem to put them together.

Bar chart :

ggplot(cost)  
  aes(x = Date, fill = Utility, weight = usage)  
  geom_bar()  
  scale_fill_hue(direction = 1)  
  theme_minimal()

Line chart :

ggplot(cost)  
  aes(x = Date, y = price, colour = Utility)  
  geom_line(size = 0.5)  
  scale_color_manual(
    values = c(Electricity = "#8E0152",
    Gas = "#276419")
  )  
  theme_minimal()

CodePudding user response:

Move the aes() commands into their specific layers and then add both layers to the plot

ggplot(cost)  
  geom_bar(aes(x = Date, fill = Utility, weight = usage))  
  geom_line(aes(x = Date, y = price, colour = Utility),  size = 0.5)  
  scale_fill_hue(direction = 1)  
  scale_color_manual(
    values = c(Electricity = "#8E0152",
               Gas = "#276419")
  )  
  theme_minimal()
  • Related