简体   繁体   English

使用 purrr:map 和 ggplot

[英]Use purrr:map with ggplot

I don't have much experience using the purrr package.我没有太多使用purrr包的经验。 I have a dataframe named data which looks like this:我有一个名为data的数据框,如下所示:

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.我需要绘制一个图,其中年份在 x 轴上,发病率在 y 轴上,但是,我需要为每个国家/地区绘制单独的图。 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.我知道如何拆分数据ggplot ,但是,我不知道如何在map函数中使用ggplot 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?编写此代码的正确方法是什么?

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.您可以使用list_plot[[1]]list_plot[[2]]等访问每个Country list_plot中的图列表。

Have you considered using facets for your plots?你有没有考虑过在你的情节中使用facet?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM