anderwyang
anderwyang

Reputation: 2411

How to draw plots and have specific name for each plot

I draw plots stored in list mp , how to make mp[["A"]] plot title is A_plot? (And mp[["B"]] plot title is 'B_plot') title=paste0(names(.),'_plot') can't get what i want

library(tidyverse)

test_data <- data.frame(
  category=c('A','A','A','B','B','B'),
  price=c(1,1,2,3,2,2),
  amount=c(1:6)
) %>% split(.$category)

mp <- map(test_data,~ ggplot(.,aes(x=price,y=amount))+
      geom_point()+labs(title=paste0(names(.),'_plot')))

mp[["A"]]

enter image description here

Upvotes: 0

Views: 33

Answers (1)

stefan
stefan

Reputation: 123783

Using purrr::imap you could do:

library(tidyverse)

mp <- imap(test_data, ~ ggplot(.x, aes(x = price, y = amount)) +
  geom_point() +
  labs(title = paste0(.y, "_plot")))

mp[["A"]]

Upvotes: 1

Related Questions