0

I try to pass the first value of Species column (after filtering) intro the paste() command for the title=. But this does not work. Could anybody suggest a solution?

It should work for whatever species I select in filter(...)

iris%>%
  filter(Species=="setosa")%>%
  ggplot(aes(Sepal.Length, Sepal.Width))+
  geom_point()+
  labs(title=paste("Length vs Width for ", Species[[1]]))

Expected outcome:enter image description here

Justas Mundeikis
  • 935
  • 1
  • 10
  • 19
  • Related: [Adding dynamic chart titles in ggplot2](https://stackoverflow.com/questions/55336983/adding-dynamic-chart-titles-in-ggplot2) – markus Apr 30 '22 at 19:38

1 Answers1

0

You don't really have access to the passed data frame within labs, since nothing is being piped to it. However, since you are already using the %>% operator, you could wrap the ggplot call in curly braces and use the . symbol as a stand-in:

iris %>%
  filter(Species=="setosa") %>% {
  ggplot(., aes(Sepal.Length, Sepal.Width)) +
  geom_point() +
  labs(title=paste("Length vs Width for ", .$Species[1]))
  }

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87