我正在尝试迭代地构建我的数据的所有可能的图表,由表格中的每一列着色.
到目前为止,我有这个代码:
# ----- next is a function taken from http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/
# --- not relevant to the question, my code is in the end of the snippet
library(ggplot2)
multiplot <- function(..., plotlist=NULL, file, cols=1, layout=NULL) {
library(grid)
# Make a list from the ... arguments and plotlist
plots <- c(list(...), plotlist)
numPlots = length(plots)
# If layout is NULL, then use 'cols' to determine layout
if (is.null(layout)) {
# Make the panel
# ncol: Number of columns of plots
# nrow: Number of rows needed, calculated from # of cols
layout <- matrix(seq(1, cols * ceiling(numPlots/cols)),
ncol = cols, nrow = ceiling(numPlots/cols))
}
if (numPlots==1) {
print(plots[[1]])
} else {
# Set up the page
grid.newpage()
pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))
# Make each plot, in the correct location
for (i in 1:numPlots) {
# Get the i,j matrix positions of the regions that contain this subplot
matchidx <- as.data.frame(which(layout == i, arr.ind = TRUE))
print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row,
layout.pos.col = matchidx$col))
}
}
}
#----------------------------------------------------------------
temp23_before6 <- data.frame(TIME = c(1, 2, 3, 4, 5),
VALUE = c(1, 2, 3, 4, 5),
P = c(1, 2, 3, 2, 1),
D = c(4, 5, 6, 7, 8))
i <- 1
p <- list()
for (col in names(temp23_before6)) {
l <-length(unique(temp23_before6[, col]))
if (l < 20 && l > 1) {
cc <- col
p[[i]] <- ggplot(temp23_before6, aes(TIME, VALUE, colour=factor(temp23_before6[, cc]))) +
geom_point() + labs(title=col)
i <- i + 1
}
}
multiplot(plotlist = p, cols = as.integer(sqrt(i)))
Run Code Online (Sandbox Code Playgroud)
不幸的cc是由于关闭没有改变,我收到的所有情节完全一样.与其他语言一起使用的常用技巧 - 分配col给局部变量 - 不起作用.如何让它在R中工作?
更新更新的代码,以便可以在新的R env中运行该示例.我希望这四个地块颜色不同.它们中的两个Time和Value应该是明显单一颜色的,而另两个P和D应该具有不同的颜色,由下式确定P = c(1, 2, 3, 2, 1), D = c(4, 5, 6, 7, 8),所以D应该有5点不同的颜色,并且P应仅具有3
这个问题更多地与hadlyverse中的编程有关.我们做了两处更改,1)添加aes_string以允许在ggplot调用中进行评估,以及2)清理要由着色列命名的图例:
p[[i]] <- ggplot(temp23_before6, aes_string("TIME", "VALUE",
colour=factor(temp23_before6[,cc]))) +
geom_point() + labs(title=col) + scale_colour_discrete(name=cc)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
117 次 |
| 最近记录: |