How to use a parameter from filter() as a parameter for labs() ? (with reprex)

Hi, folks

I want to take two variables from a data frame and uses them to filter rows of interest and write the title of my graph.

I filtered my data frame by year == 2017 and by type == "A". When I wrote my labs(), I tried: labs(title = paste0("Year: ", year), but it failed.

I wanted to have a final plot whose title was the year, in this case, 2017. Is it possible?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(ggplot2)

# Generate fake data ---------------------------------------------------------------------
set.seed(125)
df = data.frame(
  year = c(rep(2017, 3), rep(2018, 3), rep(2019, 3)),
  type = rep(c("A", "B", "C"), 3),
  month = rep(c("Jan", "Feb", "Mar"), 3),
  signal = round(c(runif(3,0,100), runif(3,1000,2000), runif(3,15000,20000)))
) %>%
  mutate(month = factor(month, levels = c("Jan", "Feb", "Mar")))


# Plotting the graph I wanted my function to generate ------------------------------------

df %>% 
  filter(year == 2017, type == "A" ) %>% 
  ggplot(aes(x = month, y = signal)) +
  geom_col(width = .2) + 
  labs(title = paste0('Year: ', year)) +
  theme_bw()
#> Error in paste0("Year: ", year): object 'year' not found

Created on 2021-02-18 by the reprex package (v1.0.0)

This fixes it.

df %>% 
  filter(year == 2017, type == "A" ) %>% 
  ggplot(aes(x = month, y = signal)) +
  geom_col(width = .2) + 
  labs(title = paste0('Year: ', df$year)) + 
  theme_bw()

another option:

filtered_year <- 2017

df %>% 
  filter(year == filtered_year, type == "A" ) %>% 
  ggplot(aes(x = month, y = signal)) +
  geom_col(width = .2) + 
  labs(title = paste0('Year: ', filtered_year)) +
  theme_bw()
1 Like

Thank you so much, @williaml. I can't believe your first solution didn't come to me. :sweat_smile:

1 Like

Use @williami's second solution. The first solution is not robust. The title will always be Year: 2017, regardless of what year you filter to. df$Year reaches outside the plot environment to the original data frame. Since 2017 is the first value of df$Year, that's what will always be used in the title. For example, run the following:

df %>% 
  filter(year == 2019, type == "A" ) %>% 
  ggplot(aes(x = month, y = signal)) +
  geom_col(width = .2) + 
  labs(title = paste0('Year: ', df$year)) + 
  theme_bw()
2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.