R 从带有数据帧的嵌套列表中绘制ggplot
这是我的数据帧R 从带有数据帧的嵌套列表中绘制ggplot,r,ggplot2,dplyr,purrr,R,Ggplot2,Dplyr,Purrr,这是我的数据帧 df <- tibble("Fruit_Name" = c("Banana", "Apple", "Orange", "Peach", "Pear", "Watermelon"), "Code" = c(1,1,2, 2,3, 3), "Share_2002" = c(0.116, 3.442, 2.445, 1.932, 0.985, 0.321), "Share_2010" = c(1.4, 2.8, 2.4, 2.10, 0.99, 1.04), "Share_201
df <- tibble("Fruit_Name" = c("Banana", "Apple", "Orange", "Peach", "Pear", "Watermelon"), "Code" = c(1,1,2, 2,3, 3), "Share_2002" = c(0.116, 3.442, 2.445, 1.932, 0.985, 0.321), "Share_2010" = c(1.4, 2.8, 2.4, 2.10, 0.99, 1.04), "Share_2018" = c(0.161, 0.232, 1.234, 0.456, 0.089, 0.06), "Share_2018_bis" = c(0.5, 0.34, 1.5, 1.2, 0.75, 1.8))
这使得我可以在x轴上绘制一个年份图,并在y轴上为每个代码组中的每个水果进行共享
我无法为ggplot指定每个嵌套数据帧!
我不想从列表中构造数据帧,但尝试访问现有的数据帧。
我试过这样的方法:
myplot <- function(x){ggplot(x, aes(x = Year, y = Share, color = Fruit_Name)) +
geom_line(size = 2) +
facet_grid(Code~ .)}
i <- c(1,2,3)
for (x in i){
lapply(fruits[["i"]], map_depth(x, 2, myplot(fruits2)))
}
myplot我认为您的示例数据中有一个输入错误,因为您没有像其他人一样重命名Share_2010,所以我从
fruits <- df %>%
rename("2002" = Share_2002,
"2010" = Share_2010,
"2018" = Share_2018,
"2018bis" = Share_2018_bis) %>%
arrange(Code)%>%
group_split(Code) %>%
map(~list(fruit_normal = .x, fruit_long = .x %>%
gather(Year, Share, c(3,4,5), -Code, -Fruit_Name) %>%
arrange(Fruit_Name) %>%
mutate_all(funs(str_replace(., "2018bis", "2018"))),
fruits2 = .x %>%
gather(Year, Share, c(3,4,6), -Code, -Fruit_Name) %>%
arrange(Fruit_Name) %>%
mutate_all(funs(str_replace(., "2018bis", "2018")))))
及
这就是你要找的吗?我不明白你想做什么。您的示例中似乎有未定义的变量,例如职业和水果长。也许水果[[i]]
应该是水果[[i]]
。但是ggplot只接受data.frames;它不接受列表的列表。你不能改变这一点。您需要确保传入data.frame进行打印。如果运行代码,您将看到列表fruits包含3个嵌套列表,每个列表包含3个数据帧(fruit\u normal、fruit\u long、fruit2)。我想为每一个子列表绘制一年,分享fruit_long和fruit_2。因此,我要传递给ggplot的参数是2个数据帧,我不知道如何访问它们,因为它们位于列表中的列表中,我也不知道如何循环它们,因为我希望每个子列表都有相同的图形。非常感谢。这是非常有用的!如果我想让同一张图上的两个图都看到2018年和2018bis之间的差异会怎样?我已经修改了包含2个数据帧的函数,但我不知道如何通过map和pulk传递它们!map2传递x和y以及函数plotFruit可能是一个好主意,但是我如何用pulk传递它们呢?非常感谢。
myplot <- function(x){ggplot(x, aes(x = Year, y = Share, color = Fruit_Name)) +
geom_line(size = 2) +
facet_grid(Code~ .)}
i <- c(1,2,3)
for (x in i){
lapply(fruits[["i"]], map_depth(x, 2, myplot(fruits2)))
}
fruits <- df %>%
rename("2002" = Share_2002,
"2010" = Share_2010,
"2018" = Share_2018,
"2018bis" = Share_2018_bis) %>%
arrange(Code)%>%
group_split(Code) %>%
map(~list(fruit_normal = .x, fruit_long = .x %>%
gather(Year, Share, c(3,4,5), -Code, -Fruit_Name) %>%
arrange(Fruit_Name) %>%
mutate_all(funs(str_replace(., "2018bis", "2018"))),
fruits2 = .x %>%
gather(Year, Share, c(3,4,6), -Code, -Fruit_Name) %>%
arrange(Fruit_Name) %>%
mutate_all(funs(str_replace(., "2018bis", "2018")))))
plotFruit <- function(df) {
ggplot(df, aes(group = Fruit_Name, x = Year, y = Share, color = Fruit_Name)) +
geom_line(size = 2) +
facet_grid(Fruit_Name~ .)}
map(fruits, pluck, "fruit_long") %>% map(plotFruit)
map(fruits, pluck, "fruits2") %>% map(plotFruit)