Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change bar colours in combined ggplot

I have the below data.frame, which has 2 utilities, Electricity & Gas, each of which has a ‘usage’ value and a ‘ price’ value. I’ve managed to plot all of these into a single plot with the ‘Usage’ being a geom_bar, and the ‘price’ being a geom_line. Would someone be able to modify my code to indicate how to change the colours for ‘Electricity’ and ‘Gas’ on the geom_bar? I can change them for the line graph, but it’s been a struggle doing it for the bar chart.

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"
))

Code for plot :

ggplot(cost) +
  geom_bar(aes(x = Date, fill = Utility, weight = usage), alpha = 0.5) +
  scale_color_manual(values = c(Electricity = 'green', 
                                Gas = 'red')) +
  geom_line(aes(x = Date, y = price, colour = Utility),  size = 0.5) +
  scale_fill_hue(direction = 1) +
  scale_color_manual(
    values = c(Electricity = "firebrick1",
               Gas = "darkorchid1")
  ) +
  theme_minimal() + scale_x_date(date_breaks = "2 month")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because you defined the fill = parameter in your geom_bar() you have to use scale_fill_manual() to change the filling of your bars. However, there is another problem with scale_fill_hue() as it gives you an error if you keep it in your code. Therefore, I removed scale_fill_hue() and changed the code as following:

library(tidyverse)

ggplot(cost) +
  geom_bar(aes(x = Date, fill = Utility, weight = usage), alpha = 0.5) +
  geom_line(aes(x = Date, y = price, colour = Utility),  size = 0.5) +
  scale_fill_manual(values = c(Electricity = 'green', Gas = 'red')) +
  scale_color_manual(values = c(Electricity = "firebrick1", Gas = "darkorchid1")) +
  scale_x_date(date_breaks = "7 day")+
  theme_minimal() + 
  theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust=1))

Created on 2022-09-13 with reprex v2.0.2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading