Knitr: the ggplot2 function call in the loop is not displayed if accompanied by some other graphing functions

I'm not sure if this is a real mistake, or I'm missing something, but here everything goes. I have a ggplot (plot_data) function that I would like to call in a loop. I included the function in my piece. A function call works fine in a loop in the case of one (a piece called "works"), in this case, the panel_data function follows the panel. However, in the second case, the plot_data () function is accompanied by a heat mask, and in this case, strangely enough, the heat map suppresses the plot_data function. This happens whether the plot () or print () function is called around the plot_data function.

Is there a way to get ggplots to behave with knitr? And how the hell is a function call overwhelming the output of a previous function call?

The following code reproduces the error for me:

[preamble omitted] \begin{document} <<setup, eval=TRUE, echo=FALSE, cache=FALSE>>= plot_data <- function(data) { require(ggplot2) require(reshape) d.melt <- melt(data) ggplot(data=d.melt, aes(x=X2, y=value, group=X1, colour=X1)) + geom_line(size=.5) + scale_x_discrete("") + scale_y_continuous("Value") } @ <<works, echo=FALSE, results='asis', out.width='.3\\linewidth', dev='pdf', cache=TRUE >>= set.seed(10010) data <- matrix(runif(10000, 1,100), ncol=100) for (i in 1:10) { ind <- sample(1:100, 10) plot(plot_data(data[ind,])) barplot(ind) } @ <<doesnt-work, echo=FALSE, results='asis', out.width='.3\\linewidth', dev='pdf', cache=TRUE >>= set.seed(10010) data <- matrix(runif(10000, 1,100), ncol=100) for (i in 1:10) { ind <- sample(1:100, 10) plot(plot_data(data[ind,])) # calling print instead of plot doesn't work either heatmap(data[ind,] ) } @ \end{document} 
+8
r knitr ggplot2
source share
2 answers

I think you ask a lot from knitr . Aligning basic graphics and graphic graphics is not very easy and difficult in R. I don’t know how knitr can be used (latex graphics package), but I think that when you call heatmap , it prints in the same place on the grid section.

Adding plot.new before calling the base graphic works fine for me:

 <<doesnt-work, fig.show='hold',out.width='.3\\linewidth'>>= set.seed(10010) data <- matrix(runif(10000, 1,100), ncol=100) for (i in 1:3) { ind <- sample(1:100, 10) print(plot_data(data[ind,])) # calling print instead of plot doesn't work either plot.new() heatmap(data[ind,] ) } @ 
+3
source share

The error is in your function, I think the variables from the melt are disabled. This worked for me:

 library(ggplot2) library(reshape2) set.seed(10010) data <- matrix(runif(10000, 1,100), ncol=100) for (i in 1:3) { ind <- sample(1:100, 10) d.melt <- melt(data[ind,]) p<-ggplot(data=d.melt, aes(x=Var1, y=Var2, group=Var1, colour=Var1)) + geom_line(size=.5) + scale_x_discrete("") + scale_y_continuous("Value") print(p) plot.new() heatmap(data[ind,] ) } 
0
source share

All Articles