Flag to print plots [duplicate] - r

I have a strange issue with Rstudio: If a script calls ggplot2 functions to display a plot, then using Source to run the script does not produce the plots. If I select the whole script with Ctrl+A, then Run the current line or selection (Ctrl+Enter), then the plot does display. Likewise, typing plotting commands into the console produces correct output.
For example:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point()
Will only produce output if pasted into console, not if sourced.
There are other questions about this, but neither is helpful:
ggplot2 ggsave function causes graphics device to not display plots falsely claims the issue is fixed in newer versions, it has not.
RStudio - ggplot not saving first plot when printing and saving multiple plots in a script was closed as a duplicate, yet not only is it not a duplicate, but the dev.off() workaround doesn't work ("Error in dev.off() : cannot shut down device 1 (the null device)")
How can I get Rstudio to display plots when a script is sourced? I am using Rstudio 0.98.1062 and R 3.1.1.

The solution is to explicitly call print() on ggplot object:
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
print(p)
ggplot function returns object of class ggplot; ggplot2 works by overloading print function to behave differently on objects of class ggplot - instead of printing them to STDOUT, it creates chart.
Everything is working well in interactive mode, because R assumes that most of commands are run through print() function. This is for our convenience and allows us to type rnorm(1) and get any visible output. When Run current selection command is used (Ctrl+Enter), RStudio behaves as if each selected line was typed in interactive mode and run. You can verify that by checking your command history in Console pane after running few selected lines.
But this convenient mode is abandoned when file is read by source(). Since this function is intended to run (potentially long and computationally-expensive) R scripts, it is undesirable to pollute STDOUT with low-priority messages. That's why source() by default will output only error message. If you want anything else, you have to explicitly ask for that.

though it's a quite old question. I had the same problem and found a quick solution, if you want to use "source" button on R studio edit box.
you can simply turn on "source with echo" (Ctrl + Shift + Enter) and the plot shows as expected

I recently happened on this question and realized that the most up to date way is to call show(p) after creating the plot.

I found this question when searching a similar problem (plots not showing up in RStudio). I was trying to troubleshoot a complicated ggplot2 block by running it in parts, but couldn't get anything to show up in the plot window.
Reason: the tiff() function I opened earlier had not closed.
Solution: I ran dev.off() a few times until all my earlier tiff() functions completed, then I was able to create plots in RStudio and view the results in the plot window.

Another option is simply using plot(). When clicking on "Source" in Rstudio, it show the plot in the window like this:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p = p + geom_point()
plot(p)
# This pops when clicking on Source
source("~/.active-rstudio-document")
Output:

Related

Julia Plots.jl Latex issue

Plotting in Julia has been a pain for me thus far. I do
using Plots.jl
Initially the plotting was fine, even with latex expressions. However, something must have changed (I don't know what), and now when I wish to plot something with latex expression in the axis or title, for example:
plot(
p1,p2,
layout=layout,
link=:y,#aligns y-axis gridlines
size = (800, 400),
xtickfontsize=15,ytickfontsize=15,
xlab="s " *L" [h^{-1}Mpc]",
ylab=L"|x_s^2\xi_l^{bisector ,(2)}(s)/\xi_l^{pp}(s)|")
I get the error message:
latex: major issue: So far, no MiKTeX administrator has checked for updates.
latex: failed to create a dvi file
Furthermore, my plots are not longer being shown in Jupyter notebook (although I save them, and when I look at what was saved, the plots are there, although with messed up Latex).
Is there any easy fix for this?
I have tried using PyPlots (and PyCall to call it from python) but seem to have an issue importing that. For now I would prefer to stick with pure Julia plotting libraries, and be able to use them with latex.

Text not displaying in ggplot2 plot using rpy2 magic

When I generate any ggplot2 plot using R magic in Jupyter Notebook, all text in the plot is rendered as little empty boxes.
My environment is running the notebook via Jupyter Hub on Ubuntu server. R magic is working great in general, with the goal of re-using some existing R code I have to output a Word Cloud via wordcloud package. However, when I generate any plot using ggplot2 any text is missing and all I see are small empty boxes.
library(ggplot2)
ggplot(mtcars, aes(x = drat, y = mpg)) +
geom_point()
see image here
The plot should show text on the axis labels but no text is displayed, just empty boxes.
Generating the same plot when running R from ssh terminal and saving it to disk (it's on a headless server) looks fine. Generating plot via pandas data frame in a different cell looks fine. So it seems related to rpy2? I'm stumped.
[EDIT]: in fact I see the same behavior using R kernel on this server, so it seems to not be specific to rpy2 / R magic.
I was able to solve this by installing all the needed packages via R install.packages() rather than conda. Next time I think I will avoid using conda for R packages altogether; this isn't the first time it has caused issues.

ggplot plots in scripts do not display in Rstudio

I have a strange issue with Rstudio: If a script calls ggplot2 functions to display a plot, then using Source to run the script does not produce the plots. If I select the whole script with Ctrl+A, then Run the current line or selection (Ctrl+Enter), then the plot does display. Likewise, typing plotting commands into the console produces correct output.
For example:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p + geom_point()
Will only produce output if pasted into console, not if sourced.
There are other questions about this, but neither is helpful:
ggplot2 ggsave function causes graphics device to not display plots falsely claims the issue is fixed in newer versions, it has not.
RStudio - ggplot not saving first plot when printing and saving multiple plots in a script was closed as a duplicate, yet not only is it not a duplicate, but the dev.off() workaround doesn't work ("Error in dev.off() : cannot shut down device 1 (the null device)")
How can I get Rstudio to display plots when a script is sourced? I am using Rstudio 0.98.1062 and R 3.1.1.
The solution is to explicitly call print() on ggplot object:
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg))
p <- p + geom_point()
print(p)
ggplot function returns object of class ggplot; ggplot2 works by overloading print function to behave differently on objects of class ggplot - instead of printing them to STDOUT, it creates chart.
Everything is working well in interactive mode, because R assumes that most of commands are run through print() function. This is for our convenience and allows us to type rnorm(1) and get any visible output. When Run current selection command is used (Ctrl+Enter), RStudio behaves as if each selected line was typed in interactive mode and run. You can verify that by checking your command history in Console pane after running few selected lines.
But this convenient mode is abandoned when file is read by source(). Since this function is intended to run (potentially long and computationally-expensive) R scripts, it is undesirable to pollute STDOUT with low-priority messages. That's why source() by default will output only error message. If you want anything else, you have to explicitly ask for that.
though it's a quite old question. I had the same problem and found a quick solution, if you want to use "source" button on R studio edit box.
you can simply turn on "source with echo" (Ctrl + Shift + Enter) and the plot shows as expected
I recently happened on this question and realized that the most up to date way is to call show(p) after creating the plot.
I found this question when searching a similar problem (plots not showing up in RStudio). I was trying to troubleshoot a complicated ggplot2 block by running it in parts, but couldn't get anything to show up in the plot window.
Reason: the tiff() function I opened earlier had not closed.
Solution: I ran dev.off() a few times until all my earlier tiff() functions completed, then I was able to create plots in RStudio and view the results in the plot window.
Another option is simply using plot(). When clicking on "Source" in Rstudio, it show the plot in the window like this:
library(ggplot2)
p = ggplot(mtcars, aes(wt, mpg))
p = p + geom_point()
plot(p)
# This pops when clicking on Source
source("~/.active-rstudio-document")
Output:

See chart in R Shell

I have a simple R script doing:
jpeg(myplot.jpg)
x<-seq(1,20,0.1)
y<-sin(x)
plot(x,y)
dev.off()
After execution it makes a myplot.jpg file in /root/work/ but renders gibberish information and does not plot a legible graph.
Also how can I view the graph in R shell itself?
The first argument to jpeg should be a character string, so I wouldn't expect your code to work unless myplot.jpg contained a character string. This works fine for me:
jpeg("myplot.jpg")
x<-seq(1,20,0.1)
y<-sin(x)
plot(x,y)
dev.off()
Whether you can view the graph in the "shell" depends on the R console you're using. If you're running R from bash, sh, etc, the answer is "no, you can't view a plot directly"... actually it wouldn't surprise me if there was a package that allowed you to create text-plots, but I don't think that's what you want.

issues of wrapping up a set of workable R commands into a function

I generate a dendrogam using a collection of r commands. It worked just fine and saved the generated dendromgram into a PDF file. To improve efficiency, I wrapped these commands as a function, which does not change anything. However, the pdf is just a blank file without any graphical content. Please let me know what’s wrong with my function defintion. Thanks.
myplot<-function(inputcsv, outputfile){
library(ggdendro)
library(ggplot2)
x<-read.csv(inputcsv,header=TRUE)
d<-as.dist(x,diag=FALSE,upper=FALSE)
hc<-hclust(d,"ave")
dhc<-as.dendrogram(hc)
ddata<-dendro_data(dhc,type="rectangle")
ddata$labels$text <- gsub("\\."," ",ddata$labels$text)
ggplot(segment(ddata))+geom_segment(aes(x=x0,y=y0,xend=x1,yend=y1))
pdf(outputfile, width=30,height=35)
last_plot()
dev.off()
}
R FAQ
Wrap your ggplot call in a print() function.
ggplot and friends return an object, and the plotting only happens when the object is printed. When you do this on the command line the printing happens automatically. When you stick it in a script or function you have to do it yourself.
The debate on whether this is a good idea or a dumb thing that just generates questions like this continues...

Resources