使用 purrr:map 和 ggplot [英] Use purrr:map with ggplot
问题描述
我没有太多使用 purrr
包的经验.我有一个名为 data
的数据框,如下所示:
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
这是机密,我不能分享,所以这只是一小部分摘录.我需要绘制一个图,其中年份在 x 轴上,发病率在 y 轴上,但是,我需要为每个国家/地区绘制单独的图.不幸的是,分面不是一种选择,我需要将每个图保存为一个单独的文件.
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.
我知道如何拆分数据帧,但是,我不知道如何在 map
函数内部使用 ggplot
.这是我尝试使用的代码,但无法正常工作.
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?
推荐答案
您可以使用:
library(tidyverse)
list_plot <- data %>%
group_split(Country) %>%
map(~ggplot(., aes(x = Year, y = Incidence) ) +
geom_line()+ geom_point())
您可以在 list_plot
中获得每个 Country
的图表列表,可以使用 list_plot[[1]]
, 访问list_plot[[2]]
等
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?
这篇关于使用 purrr:map 和 ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!