Introduction

Energy conservation is an important part of sustainability. Reducing electricity use can help lower energy demand and improve energy efficiency. Data visualization can make energy-use patterns easier to understand and communicate.

This code-through demonstrates how to use ggplot2 in R to visualize household electricity use before and after energy-conservation practices are introduced.

This code-through expands on the ggplot2 visualization techniques used in class by applying them to a sustainability-focused example involving household electricity conservation.


Content Overview

This code-through will demonstrate how to:

Create a simple household energy-use dataset

Calculate electricity savings

Reshape data for use with ggplot2

Create a line graph comparing electricity use

Create a bar graph showing energy savings

Calculate total and percentage energy savings

Interpret the graphs from a sustainability perspective


Why You Should Care

Sustainability professionals often work with data related to energy use, water use, waste, emissions, and other environmental indicators. Looking at numbers in a table can make it difficult to quickly recognize patterns.

Graphs can make changes easier to see. For example, electricity use can be compared before and after conservation efforts to determine whether energy consumption decreased.

Using visualization also makes sustainability information easier to communicate to people who may not work directly with data.

The same visualization techniques used in this code-through could also be applied to water conservation, greenhouse gas emissions, recycling, renewable energy, or other sustainability topics.


Learning Objectives

By the end of this code-through, you should be able to:

Create a simple dataset in R.

Calculate a new variable using mutate().

Reshape data using pivot_longer().

Create a line graph using ggplot2.

Create a bar graph using ggplot2.

Calculate total and percentage energy savings.

Interpret patterns shown in a sustainability visualization.



Creating the Energy Dataset

For this example, I created a small dataset representing monthly household electricity use. Electricity use is measured in kilowatt-hours, or kWh.

The before column represents electricity use before energy-conservation practices were introduced. The after column represents electricity use after conservation practices were introduced.

energy <- data.frame(
  month = factor(
    c(
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August"
    ),
    levels = c(
      "January",
      "February",
      "March",
      "April",
      "May",
      "June",
      "July",
      "August"
    )
  ),
  
  before = c(
    1250,
    1180,
    1050,
    980,
    1100,
    1350,
    1500,
    1475
  ),
  
  after = c(
    1100,
    1030,
    930,
    850,
    950,
    1160,
    1275,
    1250
  )
)

energy

The dataset contains eight months of electricity use.

Creating the month variable as a factor keeps the months in calendar order when they are displayed in the graphs.

Calculating Energy Savings

A new variable can be created to show how much electricity was saved each month.

Electricity savings are calculated by subtracting electricity use after conservation from electricity use before conservation.

energy <- energy %>%
  mutate(
    energy_saved = before - after
  )

energy

The mutate() function adds a new column called energy_saved.

A positive value means electricity consumption was lower after the conservation practices were introduced.

For example, January electricity use decreased from 1,250 kWh to 1,100 kWh.

The amount saved can be calculated by subtracting the after value from the before value.

1250-1100

The result is 150 kWh saved during January.

Reshaping the Data for ggplot2

The dataset currently has separate columns for electricity use before and after conservation.

To make the two groups easier to compare in the same graph, the data can be changed from a wide format to a long format using pivot_longer().

energy_long <- energy %>%
  select(month, before, after) %>%
  pivot_longer(
    cols = c(before, after),
    names_to = "period",
    values_to = "kwh"
  )

energy_long


What’s more, it can also be used for…

# Some code

Instead of having separate before and after columns, the new dataset has a variable called period that identifies whether the measurement was taken before or after conservation.

The electricity measurements are stored in the kwh variable.

This format makes it easier to tell ggplot2 to create separate lines for the two groups.

#Comparing Electricity Use with ggplot2

A line graph can be used to compare electricity use before and after conservation across the eight months.

ggplot(
  data = energy_long,
  aes(
    x = month,
    y = kwh,
    group = period,
    color = period
  )
) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +
  labs(
    title = "Household Electricity Use Before and After Conservation",
    subtitle = "Monthly electricity consumption measured in kilowatt-hours",
    x = "Month",
    y = "Electricity Use (kWh)",
    color = "Period"
  ) +
  theme_minimal()

The first part of the graph identifies the dataset and variables.

x = month places the months on the horizontal axis.

y = kwh places electricity consumption on the vertical axis.

group = period separates the before and after observations.

color = period gives each group a separate appearance.

The geom_line() function connects the monthly observations with lines.

The geom_point() function adds a point for each monthly observation.

The labs() function adds the title, subtitle, axis labels, and legend title.

The theme_minimal() function creates a simple graph style that keeps the focus on the data.

The graph makes it easier to see that electricity use after conservation is lower than electricity use before conservation during each month.



#Visualizing Electricity Savings

The amount of electricity saved each month can also be displayed directly using a bar graph.

ggplot(
  data = energy,
  aes(
    x = month,
    y = energy_saved
  )
) +
  geom_col() +
  labs(
    title = "Monthly Electricity Savings",
    subtitle = "Reduction in electricity use after conservation practices",
    x = "Month",
    y = "Electricity Saved (kWh)"
  ) +
  theme_minimal()

In this graph, the height of each bar represents the amount of electricity saved during that month.

geom_col() is useful when the values that determine the height of the bars are already included in the dataset.

This graph focuses on the difference between the before and after measurements instead of displaying both measurements separately.

Calculating Total Electricity Savings

total_saved <- sum(energy$energy_saved)

total_saved
## [1] 1340

Across the eight months, the household saved r total_saved kWh of electricity.

The total electricity use before and after conservation can also be calculated.

total_before <- sum(energy$before)

total_after <- sum(energy$after)

total_before
## [1] 9885
total_after
## [1] 8545

The percentage reduction in electricity use can then be calculated.

percent_saved <- 
  (total_before - total_after) /
  total_before * 100

round(percent_saved, 1)
## [1] 13.6

Overall electricity consumption decreased by approximately r round(percent_saved, 1)% in this example.


#What Can We Learn From the Visualization?

The graphs make the differences in electricity consumption easier to recognize than looking at the raw numbers alone.

Electricity use after conservation is lower during every month in the example dataset.

The line graph also shows that electricity use changes across the year. Electricity consumption is highest during July and August in this example. However, electricity use after conservation remains lower than the before-conservation amount even during these higher-use months.

The bar graph provides another perspective because it focuses specifically on how much electricity was saved each month.

Together, these visualizations show how ggplot2 can be used to communicate energy-use patterns and evaluate conservation efforts.


#Other Sustainability Applications:

The same R and ggplot2 techniques could be used with many other types of sustainability data.

Examples include:

Comparing household water use before and after water-conservation efforts

Tracking waste generation over time

Comparing recycling rates

Visualizing greenhouse gas emissions

Comparing renewable and nonrenewable energy production

Tracking transportation emissions

Comparing energy use between buildings

Monitoring sustainability indicators over time

Changing the dataset would allow the same basic graph structure to answer different sustainability questions.


# Further Resources

The following resources provide additional information for readers who want to learn more about the tools and sustainability topics demonstrated in this code-through.

The official documentation for the ggplot2 package provides additional examples of graphs, aesthetics, layers, labels, and themes.

This online book provides more information about data visualization, data transformation, and working with data in R.

The U.S. Energy Information Administration provides information and datasets related to residential energy consumption.


Learn more about [package, technique, dataset] with the following:


Works Cited

U.S. Energy Information Administration. Residential Energy Consumption Survey. U.S. Department of Energy. https://www.eia.gov/consumption/residential/

Wickham, H., Çetinkaya-Rundel, M., and Grolemund, G. R for Data Science (2e). https://r4ds.hadley.nz/

Wickham, H., et al. ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics. https://ggplot2.tidyverse.org/