Use purrr:map with ggplot

妖精的绣舞 提交于 2020-06-29 04:04:32

问题


I don't have much experience using the purrr package. I have a dataframe named data which looks like this:

Country Year Incidence
USA     1995 20000
USA     2000 23000
UK      1995 16000
UK      2000 22000

It's confidential and I can't share it so this is just a small excrept. I need to make a plot where Year is on x-axis and incidence on y-axis, however, I need to have separate plots for each country. Faceting is unfortunately not an option, I need to save each plot as a separate file.

I know how I would split the dataframe, however, I don't know how to use ggplot inside of the map function. This is the code that I was trying with and is not working.

data %>%
  group_by(Country) %>%
  group_split() %>%
  map(ggplot, aes(x = Year, y = Incidence)+
        geom_line()+
        geom_point())

What would be the proper way to write this code?


回答1:


You can use :

library(tidyverse)

list_plot <- data %>%
               group_split(Country) %>%
               map(~ggplot(., aes(x = Year, y = Incidence) ) +
                       geom_line()+ geom_point())

You get list of plots in list_plot one for every Country which can be accessed using list_plot[[1]], list_plot[[2]] etc.

Have you considered using facets for your plots?



来源:https://stackoverflow.com/questions/60671310/use-purrrmap-with-ggplot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!