gpt4 book ai didi

r - 在一个 ggplot() 中生成多个 ggplot 图形

转载 作者:行者123 更新时间:2023-12-04 15:56:42 25 4
gpt4 key购买 nike

我想使用相同的 ggplot 代码以我的数据框中的数字为条件生成 8 个不同的数字。通常我会使用 facet_grid,但在这种情况下,我希望最终得到每个单独数字的 pdf。例如,我想要这里的每一行一个 pdf:

df <- read.table(text = "
xvalue yvalue location planting crop
1 5 A early corn
2 3 A late corn
6 2 A early soy
7 4 A late soy
4 7 S early corn
2 6 S late corn
3 2 S early soy
5 1 S late soy
", sep = "", header = TRUE)

基本的ggplot:
library(ggplot2)

ggplot()+
geom_point(aes(x=xvalue, y=yvalue), data=df)

但不是 facet_grid为了获得位置 x 种植 x 裁剪组合,我想要每个的单独 pdf。

最佳答案

这是另一种方法:

library(plyr)
library(ggplot2)

df <- read.table(text = "
xvalue yvalue location planting crop
1 5 A early corn
2 3 A late corn
6 2 A early soy
7 4 A late soy
4 7 S early corn
2 6 S late corn
3 2 S early soy
5 1 S late soy
", sep = "", header = TRUE)

fplot <- function(d)
{
require(ggplot2)
p <- ggplot(d, aes(x = xvalue, y = yvalue)) +
geom_point(size = 4) +
xlim(0, 10) + ylim(0, 10)
file <- with(d, paste0(paste(planting, crop, location, sep = "_"), ".pdf"))
ggsave(file, p)
}

d_ply(df, ~ rownames(df), fplot)

文件名看起来像 early_corn_A.pdf 并保存在您当前的工作目录中。为了视觉方便,我设置了固定的 x/y 限制。该函数需要
一行数据框作为输入并以pdf形式输出一个图。 plyr::d_ply()函数处理数据框的每一行并为每行生成一个单独的图。

关于r - 在一个 ggplot() 中生成多个 ggplot 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30312135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com