I have issue with plotting lines over my existing plot in .Rmd in RStudio. I ran the code within the code chunk in .Rmd (⌘ + return) and the plot gives me a graph within the .Rmd (new feature of RStudio v1.0), however when I ran the second code lines, an error shows up.
plot(density(with$glucose),
ylim = c(0.00, 0.02),
xlab = "Glucose Level",
main = "Figure",
lwd = 2)
lines(density(without$glucose),
col = "red",
lwd = 2)
Error in plot.xy(xy.coords(x, y), type = type, ...) : plot.new has not been called yet
On the other hand, if I copy and paste the codes into the console, I could get the plot I want, in the plot viewer within RStudio.
In addition, when I ran some other codes within the .Rmd (⌘ + return), my plots in the plot viewer in RStudio disappear. This means I have to do copy-paste into the console instead of using the (⌘ + return) shortcut.
Does anyone have the same problem?
This is a known problem, but you can solve it very easy: Press Ctrl+Shift+Enter to run the complete chunk, then everything works fine and you don't have to copy-and-paste all thing to the console.
So do all your plots in one chunk and run this chunk. This will produce you the plot within the RMD file (as you mentioned: new feature of RStudio 1.0)
If you're not a fan of the inline output / notebook mode for R Markdown documents, you can also disable it within the Global Options dialog -- try disabling the option:
Show output inline for all R Markdown document
Related
(Newb to R)
Writing a Qmd file for a report for a small project (partly to learn R for future projects)
Running each chunk whilst is editor works fine
source("MyGraphFile", local = knitr::knit_global())
mycommand_fromgraphfile
#generating a simple histogram
The code from the Graphs R file "MyGraphFile":
mycommand_fromgraphfile <-
ggplot(mydata, aes(agey))+
geom_histogram(color = 'white',
fill = scico::scico(1, begin = .3, palette = "berlin"),
bins = 20) +
labs(x = "Age",
y = "Count") +
scale_y_continuous(
breaks = scales::pretty_breaks()
)
When I go to render this as html, pdf etc. I get this error when it runs the first chunk above with source("MyGraphFile....
Quitting from lines 29-32 (report.qmd)
Error in ggplot(mydata, aes(ageyears)) :
object 'mydata' not found
Calls: .main ... eval -> source -> withVisible -> eval -> eval -> ggplot
As I say, when running each chunk sequentially from the source/visual editor all works fine
I only get the above error when rendering the file
I've also tried simply running the whole ggplot command from within the qmd file, and not sourcing back to the graph R file, same error.
It seems the qmd file can't see the datafile when rendering? I've tested it with some of the example datasets and it renders fine, so clearly something I've missed. I've tried saving the datafile from previous cleaning and loading at the beginning of the qmd file, no luck
Any help for a n00b?
My question has been answered
The Quarto render needs the dataset loading
I'm trying to run plot(), and I can't get the default axis labels or titles to show up on either the x or y axes. The last time I ran this code, it worked just fine. Both R and R Studio have been updated within the last month, and I've tried closing and restarting R Studio. I have the same issue with both my own data and built in data, such as the iris data set. As you can see, without repressing the axis labels and titles, no axis labels and titles are added to the plot of sepal length by species.
plot(iris$Species, iris$Sepal.Length)
I think not seeing axis labels and titles is a symptom of a larger issue, as I'm also having difficulty adding any labels or titles using commands like title(ylab="Sepal Length", line=2.5, cex.lab=1, family = "Calibri Light"). Either the code runs without error and no label appears (if I don't specify font family), or I get an error message font family not found. I've tried adding the extrafonts package and using fonts that I know are installed in that package, but I get this error regardless. It seems there's something preventing me from adding any text to base R plots. Any insights would be much appreciated.
I've encountered this before and I think it is just a bug in R studio. Click the button that says clear all plots (the little broomstick) and it should perform as expected with the sample data.
Thanks - I was having the same issue but the "broomstick" did not work for me.
But I did confirm that this seems to be RStudio issue as when I output to a different graphics device the text is there.
Here's the MWE that I was trying:
library(extrafont)
#font_import(pattern = 'calibri')
#Works fine
dev.off()
plot(1,1)
text(1, 1, "Hello World", pos = 1)
# Specify Calibri through par
dev.off()
par(family = fonts()[1])
plot(1,1)
text(1, 1, "Hello World", pos = 1)
# No text, no axes
text(1, 1, "Hello World", pos = 1)
# a second call is not a solution
text(1, 1, "Hello World", pos = 1, cex = 0.7)
# is cex a solution - still no axes
axis(1, cex = 5) #not printing regardless of cex
mtext(1, text = 'Hello World') #and mtext doesn't print either
I encountered the same problem on Mac OS 11.2.1; R 4.0.3
Restarting R Session within RStudio did not solve it.
Shutting down Rstudio and restarting did not solve it.
Launching the actual R application did not solve it.
I finally did a Restart of my machine, and then everything works fine.
I originally ran into the problem after I used dev.copy(png, file="xxx.png"); dev.off()
But now of course this works fine.
So some more information, but I don't think it will ultimately "solve" the issue. Sorry.
How to display a window with a ggplot figure when executing an R script from the command line (without intermediary save to file)?
Example script test.R
#!/usr/bin/env Rscript
library(ggplot2)
p = ggplot(aes(x = Sepal.Length), data = iris) + geom_histogram(color = 'black', fill = NA)
plot(p)
On the command line run the script with ./test.R.
This dumps the plot to Rplots.pdf - instead I'd like a window just like in an interactive session with the plot, with no file output.
How to specify output device to be the screen? (e.g. on Ubuntu)
You can do this via a call to X11(), which will open a graphics window. Some relevant excerpts from help("X11"):
on Unix-alikes ‘X11’ starts a graphics device driver for the X
Window System (version 11). This can only be done on
machines/accounts that have access to an X server.
Usage:
X11(display = "", width, height, pointsize, gamma, bg, canvas,
fonts, family, xpos, ypos, title, type, antialias)
Arguments:
display: the display on which the graphics window will appear. The
default is to use the value in the user's environment
variable ‘DISPLAY’. This is ignored (with a warning) if an
X11 device is already open on another display.
However, it will close immediately after the R script is done being executed. So, this works to display your plot, but it isn't open for long:
#!/usr/bin/env Rscript
library(ggplot2)
p = ggplot(aes(x = Sepal.Length), data = iris) +
geom_histogram(color = 'black', fill = NA)
X11()
plot(p)
I guess the real questions are
Why are you averse to saving the plot before viewing it? and
If you want to open a plot window but not save the plot, why not just run your commands in an interactive R session? That seems to me more useful if you're not saving results.
I'm trying to execute the below code that display a plot:
using Plots, Measures
pyplot()
data = [rand(100), rand(100)];
histogram(data, layout = 2,
title = ["Dataset A" "Dataset B"], legend = false,
ylabel = "ylabel", margin = 5mm)
I do not get any output once I execute it from the command line!!
Knowing that I tried it in 3 different ways and it works (Jupyter, Juni, Julia session), though I'm confused about the way it works in the Juno, kinldy see my observations below:
With Jupyter it is functioning perfectly:
With Juno, I've to run the file TWICE!! the first time looks to be for compilation, second time for execution, maybe!!
And if I closed the plot, I've to close the Julia session, restart it, then re-execute the file TWICE!! and sometimes nothing is appearing!!
With Julia session, it take time for first time execution, then if I closed the plot and run it again, it is appearing smoothly.
The commands like histogram or plot typically don't display the plots for users, they only generate and return the plots.
What displays the plots is actually the display system in Julia.
When Julia is in interactive use, like in REPL, Jupyter and Juno, the display system will be invoked automatically with commands not ending with ";". That's why you see plots displayed in REPL, Jupyter and Juno.
But when executing the file from the command line, the display system is not automatically activated. So you first have to invoke display yourself like this:
using Plots, Measures
pyplot()
data = [rand(100), rand(100)];
h = histogram(data, layout = 2,
title = ["Dataset A" "Dataset B"], legend = false,
ylabel = "ylabel", margin = 5mm)
display(h)
But even this will not give you the picture, but only text representation of the plot. This is because in command line julia, only a very simple text display system is in place, and it doesn't have "full" support for plots from Plots. To display the plots, you have to write your own display mechanism and push it to Julia display system, which is not hard but a little tedious. I will give an example when I have more time.
BTW, if you just want plots generated from command line, another way is to save it to files, which is more direct than making a display mechanism yourself.
Update
Here is a simple display, which mimics the display system used in Julia REPL. The code here is for Julia 0.7/1.0.
const output = IOBuffer()
using REPL
const out_terminal = REPL.Terminals.TerminalBuffer(output)
const basic_repl = REPL.BasicREPL(out_terminal)
const basic_display = REPL.REPLDisplay(basic_repl)
Base.pushdisplay(basic_display)
Using it before the previous code will show the plot. Please note that you use pyplot() backend for Plots, whose default is to open a new window and display the plot in the window, but when the julia finish execution in the command line, it will close the plot window. To deal with this, we could either change ways for the default display, or use another backend to show the plot, for example, plotly() backend will display the plot through html. The complete code may look like following:
const output = IOBuffer()
using REPL
const out_terminal = REPL.Terminals.TerminalBuffer(output)
const basic_repl = REPL.BasicREPL(out_terminal)
const basic_display = REPL.REPLDisplay(basic_repl)
Base.pushdisplay(basic_display)
using Plots, Measures
plotly()
data = [rand(100), rand(100)];
h = histogram(data, layout = 2,
title = ["Dataset A" "Dataset B"], legend = false,
ylabel = "ylabel", margin = 5mm)
display(h)
Use readline() to get such destination that close the plot window by typing enter.
using GR
y = rand(20,1)
p = plot(y,linewidth=2,title="My Plot")
readline()
I'm having trouble with exporting eps files from R and importing into Word 2010.
I'm using ggplot2 plots, eg
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
Even after calling setEPS() neither of the following produce files which can be successfully imported.
ggsave("plot.eps")
postscript("plot.eps")
print(p)
dev.off()
The strange thing is that if I produce the plot using File -> Save As -> Postscript from the menu in the GUI, it can be imported correctly. However, when the Word document is subsequently exported as a pdf, the fonts in the graphic are a little jagged.
So my questions are:
What combination of (ggsave/postscript) settings allows me to produce eps files that can be imported into Word 2010?
How can I ensure the fonts remain clear when the Word document is exported as a pdf?
Update
After more investigation I have had more luck with cairo_ps to produce the plots. However, no text shows up when imported into Word.
Furthermore, after checking the various eps outputs (cairo_ps, save from the GUI, ggsave) in a latex document, it seems like the eps import filter in Word quite poor as the printed/pdf output doesn't match the quality of the latex'd document. The ggsave version (which uses postscript) did have some issues with colours that the other two methods didn't have though.
The conclusion is that this is a Word issue and therefore fortune(109) does not apply. I'd be happy to be proven otherwise, but I'll award the answer and the bounty to whoever can provide the commands that can replicate the output from the GUI in command form.
This worked for me... following advice in the postscript help page:
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE, onefile = FALSE,
paper = "special")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth()
p
#geom_smooth: method="auto" and size of largest group is <1000, so using loess. Use 'method = x' to #change the smoothing method.
#Warning message:
#In grid.Call.graphics(L_polygon, x$x, x$y, index) :
# semi-transparency is not supported on this device: reported only once per page
dev.off()
#quartz
# 2
The funny stuff at the end puts you on notice that this is only a Mac-tested solution, so far anyway.
Edit: I just tested it with R version 2.15.1 (2012-06-22) -- "Roasted Marshmallows": Platform: i386-pc-mingw32/i386 (32-bit) and MS Word 2007 in Win XP and it worked. Commands were Insert/Picture.../select eps format/select file.
Edit2: There is another method for saving besides directly using the postscript device. The savePlot method with an "eps" mode is available in Windows (but not in the Mac). I agree that the fonts are not as smooth as they appear on a Mac but I can discern no difference in quality between saving with savePlot and using save as from an interactive window.
savePlot(filename = "Rplot2", type = "eps", device = dev.cur(), restoreConsole = TRUE)
savePlot calls (.External(CsavePlot, device, filename, type, restoreConsole))
I solved the problem with exporting .eps files from R and importing into Word 2010 on Windows 7 using the colormodel="rgb" option (defaults to "srgb") of the postscript command.
postscript("RPlot.eps", height = 4, width = 4, horizontal = FALSE,
paper = "special", colormodel = "rgb")
library(ggplot2)
p <- qplot(disp,hp,data=mtcars) + stat_smooth(se=FALSE, method="loess")
p
dev.off()
You are probably better of using wmf as a format which you can create on Windows.
Word indeed doesn't support EPS very well.
A better solution is to export your graphs to Word or Powerpoint directly in native Office format. I just made a new package, export, that does exactly that, see
https://cran.r-project.org/web/packages/export/index.html and
for demo
https://github.com/tomwenseleers/export
Typical syntax is very easy, e.g.:
install.packages("export")
library(export)
library(ggplot2)
qplot(Sepal.Length, Petal.Length, data = iris, color = Species,
size = Petal.Width, alpha = I(0.7))
graph2doc(file="ggplot2_plot.docx", width=6, height=5)
graph2ppt(file="ggplot2_plot.pptx", width=6, height=5)
Output is vector format and so fully editable after you ungroup your graph in Word or Powerpoint. You can also use it to export statistical output of various R stats objects.
You can use R studio to knit html files with all of your plots and then open HTML files with Word.
knitr tutorial