Horje
Home Energy Usage Monitoring Dashboard in R

Home energy monitoring is important for understanding consumption patterns, optimizing energy use, and reducing costs for better household management. R is a statistical programming language popularly used for data analysis because of the packages and libraries it offers. This article will discuss how to monitor a dashboard for home energy usage in R programming language with the help of Machine Learning.

Need for Home Energy Usage Monitoring

There are multiple reasons to use monitoring for home energy consumption:

  1. Rising Energy Costs: This management will help in cost-cutting by identifying the highest energy consumption.
  2. Environmental Impact: Reducing energy consumption has a significant positive impact on the environment.
  3. Health and Comfort: Efficient energy management can enhance home comfort and health.
  4. Financial Planning and Budgeting: Understanding energy consumption patterns helps in better financial planning and budgeting.
  5. Increasing Awareness and Responsibility: As a responsible citizen we must not waste energy and this monitoring will help the cause.

Loading and Understanding the dataset

This article will use an external dataset from the Kaggle website on Household Power Consumption.

Dataset Link: Household Power Consumption

R
# Load necessary libraries
library(tidyverse)
library(lubridate)
library(ggplot2)

# Load the dataset
data <- read.csv("household_power_consumption.txt")

# Convert Date and Time to datetime format
data <- data %>%
  mutate(DateTime = dmy_hms(paste(Date, Time)),
         Global_active_power = as.numeric(Global_active_power),
         Global_reactive_power = as.numeric(Global_reactive_power),
         Voltage = as.numeric(Voltage),
         Global_intensity = as.numeric(Global_intensity),
         Sub_metering_1 = as.numeric(Sub_metering_1),
         Sub_metering_2 = as.numeric(Sub_metering_2),
         Sub_metering_3 = as.numeric(Sub_metering_3)) %>%
  filter(!is.na(Global_active_power))  

# Display the first few rows of the data
head(data)

Output:

        Date     Time Global_active_power Global_reactive_power Voltage Global_intensity
1 16/12/2006 17:24:00                2080                   189     969               53
2 16/12/2006 17:25:00                2652                   198     848               81
3 16/12/2006 17:26:00                2659                   229     814               81
4 16/12/2006 17:27:00                2666                   231     859               81
5 16/12/2006 17:28:00                1805                   244    1053               40
6 16/12/2006 17:29:00                1732                   241     987               36
  Sub_metering_1 Sub_metering_2 Sub_metering_3            DateTime
1              2              3             17 2006-12-16 17:24:00
2              2              3             16 2006-12-16 17:25:00
3              2             14             17 2006-12-16 17:26:00
4              2              3             17 2006-12-16 17:27:00
5              2              3             17 2006-12-16 17:28:00
6              2             14             17 2006-12-16 17:29:00

Preprocessing the Data

Identify and handle missing or incomplete data appropriately.

R
data <- data %>%
  filter(!is.na(Global_active_power)) 

# Example: Log transformation
data <- data %>%
  mutate(Log_Global_active_power = log(Global_active_power + 1)) 

# Example: Aggregating to daily energy consumption
daily_energy <- data %>%
  mutate(Date = as_date(DateTime)) %>%
  group_by(Date) %>%
  summarise(Daily_Consumption_kWh = sum(Global_active_power, na.rm = TRUE))

Time Series Analysis

Time series analysis helps in understanding how energy consumption varies over time. Daily energy consumption trends can highlight unusually high or low usage days, helping to identify patterns or events that lead to these variations.

R
# Aggregate data to daily energy consumption
daily_energy <- data %>%
  mutate(Date = as_date(DateTime)) %>%
  group_by(Date) %>%
  summarise(Daily_Consumption_kWh = sum(Global_active_power, na.rm = TRUE))

# Plot daily energy consumption
ggplot(daily_energy, aes(x = Date, y = Daily_Consumption_kWh)) +
  geom_line(color = "blue") +
  labs(title = "Daily Energy Consumption", x = "Date", y = "Energy Consumption (kWh)") +
  theme_minimal()

Output:

gh

Home Energy Usage Monitoring Dashboard in R

With the help of a graph, we can understand the energy consumption reduced.

Energy Consumption Trends Dashboard

Analyzing the trends on a dashboard can help us realize the ups and downs in energy consumption as well as the factors that influence these trends. The time line plays an important role in proper resource management.

R
# Load necessary libraries
library(shiny)
library(tidyverse)
library(lubridate)
library(plotly)

# Assuming 'data' is already loaded and cleaned

# Define UI for application
ui <- fluidPage(
  titlePanel("Energy Consumption Trends Dashboard"),
  sidebarLayout(
    sidebarPanel(
      dateRangeInput("daterange", "Date range:", 
                     start = min(data$DateTime), 
                     end = max(data$DateTime),
                     format = "yyyy-mm-dd", separator = " - ")
    ),
    mainPanel(
      plotlyOutput("lineChart"),
      plotOutput("barGraph"),
      plotlyOutput("heatmap")
    )
  )
)

# Define server logic
server <- function(input, output) {
  
  # Reactive expression to filter data based on date range input
  filtered_data <- reactive({
    data %>%
      filter(DateTime >= input$daterange[1] & DateTime <= input$daterange[2])
  })
  
  # Aggregate data to daily energy consumption
  daily_energy <- reactive({
    filtered_data() %>%
      mutate(Date = as.Date(DateTime)) %>%
      group_by(Date) %>%
      summarise(Daily_Consumption_kWh = sum(Global_active_power, na.rm = TRUE))
  })
  
  # Plot daily energy consumption (Line chart)
  output$lineChart <- renderPlotly({
    plot_ly(daily_energy(), x = ~Date, y = ~Daily_Consumption_kWh, type = 'scatter', 
            mode = 'lines') %>%
      layout(title = "Daily Energy Consumption", xaxis = list(title = "Date"), 
             yaxis = list(title = "Energy Consumption (kWh)"))
  })
  
  # Aggregate data to hourly energy consumption
  hourly_energy <- reactive({
    filtered_data() %>%
      mutate(Hour = hour(DateTime)) %>%
      group_by(Hour) %>%
      summarise(Hourly_Consumption_kWh = sum(Global_active_power, na.rm = TRUE))
  })
  
  # Plot hourly energy consumption (Bar graph)
  output$barGraph <- renderPlot({
    ggplot(hourly_energy(), aes(x = factor(Hour), y = Hourly_Consumption_kWh)) +
      geom_bar(stat = "identity", fill = "blue") +
      labs(title = "Hourly Energy Consumption", x = "Hour of Day", 
           y = "Energy Consumption (kWh)") +
      theme_minimal()
  })
  
  # Create heatmap for energy consumption density
  output$heatmap <- renderPlotly({
    # Aggregate data to create heatmap
    heatmap_data <- filtered_data() %>%
      mutate(Date = as.Date(DateTime), Hour = hour(DateTime)) %>%
      group_by(Date, Hour) %>%
      summarise(Avg_Active_Power = mean(Global_active_power, na.rm = TRUE)) %>%
      ungroup() %>%
      complete(Date, nesting(Hour), fill = list(Avg_Active_Power = 0))
    
    plot_ly(heatmap_data, x = ~Hour, y = ~Date, z = ~Avg_Active_Power, 
            type = "heatmap") %>%
      layout(title = "Energy Consumption Heatmap", xaxis = list(title = "Hour of Day"), 
             yaxis = list(title = "Date"))
  })
}

# Run the application
shinyApp(ui = ui, server = server)

Output:

household-bar-chart-GFG

Home Energy Usage Monitoring Dashboard in R

We can observe that the consumption is low and it increases from the 6th hour of the day.

household-heatmap-GFG

Home Energy Usage Monitoring Dashboard in R

Interactive Energy Usage Monitoring Dashboard in R

Utilizing packages like shinydashboard, plotly, and leaflet to create interactive and visually appealing dashboards.

R
# Install necessary packages
if (!require(shiny)) install.packages("shiny")
if (!require(shinydashboard)) install.packages("shinydashboard")
if (!require(plotly)) install.packages("plotly")
if (!require(leaflet)) install.packages("leaflet")

# Load packages
library(shiny)
library(shinydashboard)
library(plotly)
library(leaflet)

# Example: Using shinydashboard for UI
ui <- dashboardPage(
  dashboardHeader(title = "Energy Usage Dashboard"),
  dashboardSidebar(
    dateRangeInput("daterange", "Date range:", 
                   start = min(data$DateTime), 
                   end = max(data$DateTime))
  ),
  dashboardBody(
    fluidRow(
      box(plotlyOutput("timeSeriesPlot"), width = 6),
      box(plotlyOutput("subMeteringPlot"), width = 6)
    ),
    fluidRow(
      box(leafletOutput("mapPlot"), width = 12)
    )
  )
)

server <- function(input, output) {
  filtered_data <- reactive({
    data %>%
      filter(DateTime >= input$daterange[1] & DateTime <= input$daterange[2])
  })
  
  output$timeSeriesPlot <- renderPlotly({
    plot_ly(filtered_data(), x = ~DateTime, y = ~Global_active_power, type = 'scatter', 
            mode = 'lines') %>%
      layout(title = "Global Active Power Over Time", xaxis = list(title = "DateTime"),
             yaxis = list(title = "Global Active Power (kW)"))
  })
  
  output$subMeteringPlot <- renderPlotly({
    plot_ly(filtered_data(), x = ~DateTime) %>%
      add_lines(y = ~Sub_metering_1, name = 'Sub_metering_1', 
                line = list(color = 'red')) %>%
      add_lines(y = ~Sub_metering_2, name = 'Sub_metering_2', 
                line = list(color = 'green')) %>%
      add_lines(y = ~Sub_metering_3, name = 'Sub_metering_3', 
                line = list(color = 'blue')) %>%
      layout(title = "Sub-Metering Over Time", xaxis = list(title = "DateTime"), 
             yaxis = list(title = "Energy Consumption (kWh)"))
  })
  
  output$mapPlot <- renderLeaflet({
    # Example: Static map as placeholder
    leaflet() %>%
      addTiles() %>%
      addMarkers(lng = -122.4194, lat = 37.7749, popup = "San Francisco")
  })
}

# Run the application
shinyApp(ui = ui, server = server)

Output:

UI-GFG-3

Home Energy Usage Monitoring Dashboard in R

Energy Saving Tips and Recommendations

Based on the insights from the dashboard:

  • Optimize Appliance Usage: With the help of sub-meter readings we can understand the appliance based energy consumption which will help us manage it.
  • Upgrade to Energy-Efficient Devices: Replace old, inefficient appliances with newer, energy-efficient models.
  • Improve Home Insulation: Ensure your home is well-insulated to reduce heating and cooling energy usage.
  • Adopt Renewable Energy: Consider installing solar panels or other renewable energy sources.

Conclusion

This article explored the active role of machine learning in our daily life requirements. We built a dashboard for power consumption analysis in a household from date to date to check for cost cutting and optimization. With the help of R programming language we built many graphs to understand the distribution of the power among appliances and how to reduce it. We also visualized the energy consumption time based to optimize it.




Reffered: https://www.geeksforgeeks.org


AI ML DS

Related
Difference Between varImp (caret) and importance (randomForest) for Random Forest in R Difference Between varImp (caret) and importance (randomForest) for Random Forest in R
Hyperparameter tuning SVM parameters using Genetic Algorithm Hyperparameter tuning SVM parameters using Genetic Algorithm
How to Get an Internship as a Marketing Analyst How to Get an Internship as a Marketing Analyst
Masked Autoencoders in Deep Learning Masked Autoencoders in Deep Learning
Internal Covariant Shift Problem in Deep Learning Internal Covariant Shift Problem in Deep Learning

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
20