我想使用相同的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)
Run Code Online (Sandbox Code Playgroud)
基本ggplot:
library(ggplot2)
ggplot()+
geom_point(aes(x=xvalue, y=yvalue), data=df)
Run Code Online (Sandbox Code Playgroud)
但是不是facet_grid为了获得x种植x作物组合的位置,我想要一个单独的pdf.
首先我把你的MWE变成了data.table因为它更快
library(data.table)
library(ggplot2)
library(gridExtra)
df <- data.table(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))
Run Code Online (Sandbox Code Playgroud)
我将您的planting和corn信息粘贴在一起以创建一个单独的列:
df[ , plantingCrop := paste(df$planting, df$crop, sep = "-") ]
Run Code Online (Sandbox Code Playgroud)
planting我创建了一个包含和的所有组合的字符向量crop。您很快就会明白原因:
plantingCrop1 <- unique(df$plantingCrop)
Run Code Online (Sandbox Code Playgroud)
我用来gridExtra在单独的页面中创建所有绘图.pdf。plantingCrop1我基本上创建了一个循环,它可以绘制与上面制作的对象中的字符一样多的图形。在每个循环中,dat是您想要绘制的子集组,由我们将和列plantingCrop粘贴在一起时的唯一组绘制。它会重复此操作,直到一切完成。plantingcrop
pdf("plantingCrop.pdf", onefile = TRUE)
for(i in 1:length(plantingCrop1)){
dat <- subset(df, plantingCrop==plantingCrop1[i])
cropPlot <- ggplot(dat, aes(xvalue,yvalue)) +
geom_boxplot(aes(color = location)) +
theme_bw() +
ggtitle(bquote(atop(.("Boxplot of Stuff"),
atop(italic(.(plantingCrop1[i])), "")))) +
labs(x = "xvalue", y = "yvalue") +
theme(legend.position = "top", legend.title=element_blank())
grid.arrange(cropPlot)
}
dev.off()
Run Code Online (Sandbox Code Playgroud)
plantingCrop我还包括使用名称作为副标题来命名文件的正确方法。通话中就是这样ggtitle。
我鼓励您在拥有更多数据时进行更改,geom_boxplot(aes(color = location))因为geom_boxplot(aes(fill = location)它可以更好地显示在图表上,但我暂时保留这种方式,以便您可以看到不同的组。
| 归档时间: |
|
| 查看次数: |
450 次 |
| 最近记录: |