I'm working with sjPlot in order to get "pretty" tables. I managed to create a really nice contingency and another table providing me with frequencies of a variable.
Everything is just nice and the way it should be - except for one thing:
I work with RStudio and when I run my code that includes several sjPlot-tables as output, I can only access the latest one. Unlike the graphics-window of RStudio, where you can click back and forth through your output, I'm stuck here with just the last table.
Is there a way to create a new tab or window or so, that I can run my code and get access to all the tables I created?
That would be super cool!
Currently, there is no history feature for the Viewer pane in RStudio. You may open the tables in your browser instead (or additional, there's an icon in the Viewer pane), so you have multiple browser tabs, each with a table output.
Or you "concat" multiple tables and show them in the Viewer pane, however, this is quite an effort to do.
# create and save first HTML-table
part1 <- sjt.lm(fit1, fit2)
# create and save second HTML-table
part2 <- sjt.lm(fit3, fit4)
# browse temporary file
htmlFile <- tempfile(fileext=".html")
write(sprintf("<html><head>%s</head><body>%s<p></p>%s</body></html>",
part1$page.style,
part1$page.content,
part2$page.content),
file = htmlFile)
viewer <- getOption("viewer")
if (!is.null(viewer)) viewer(htmlFile) else
utils::browseURL(htmlFile)
Thanks Daniel!
That actually really helps a lot!
I also figured out (which is why I'm posting this as an answer and not just as a comment...) that windows() also creates new data windows through RStudio.
This might be interesting to other RStudio users as well :-)
Here's some example code just quickly copied out of my script:
scatter <- ggplot(na.action=na.exclude, spending.analysis, aes(age, money))
windows()
scatter +
geom_point(aes(color = school), alpha = 0.7) +
geom_smooth( method = "lm", color = "dark blue", alpha = 0.05, fill = "blue", na.action = na.exclude) +
facet_grid(. ~ school) +
theme_bw() +
scale_color_manual(values = group.colors)
I think this explains where to put the windows() command
Related
I'm trying to knit a PDF document and set the following global settings because I want all the code and comments to appear inside the document (otherwise long lines of code or comments extend beyond the border of the page):
knitr::opts_chunk$set(message=FALSE, tidy.opts=list(width.cutoff=40), tidy=TRUE)
The problem is that tidy=TRUE also causes some of my code to display on the same line despite being on a new line in my script. So this chunk:
ggplot(data = keffects_20, aes(x = k, y = avg_tests, group = pool_size)) +
geom_boxplot() +
xlab("Pool Size (k)") +
ylab("Mean Number of Tests per Person") +
scale_y_continuous(breaks = seq(0, 1.25, 0.25)) +
theme_classic()
actually appear as this.
But I'd like it to look like this (the same way it is written in the chunk).
The only way I'm able to get that desired format is by setting tidy=FALSE but then that causes my long lines of code to run off of the page. Is there any way to get both my long lines of code to stay on the page while also having new lines appear on a new line?
I think the tidy = FALSE option is the only way to do what you want. But you can limit that to just one statement by putting that statement in a chunk by itself.
Even better: write your source in the format you want from the beginning, or format it in the source document, and leave tidy = FALSE in all chunks.
My plots tab doesn't work - so I am trying to display the output of ggplot in the Viewer tab.
This has been accomplished for printing HTML tables: Force rstudio to use browser instead of viewer. Can this be done for plots?
library(ggplot2)
gg.plot <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
Is there a method to print to viewer?
I posted this as a comment, but couldn't get the formatting right, so I'm making it an answer. This code will create a new window to put your plot in.
library(ggplot2)
data(iris)
x11() # creates the new window
ggplot(data = iris, aes(Petal.Length)) + geom_histogram()
dev.off() # closes the window when you're done with it
Unfortunately, I don't think this is what the viewer pane was designed for. This article from Ian Pylvainen suggests that this pane is exclusively for web content. Unless you were attempting to visualise your plots in an HTML instance (produced from Markdown, Shiny, htmlwidgets, etc.), I would not recommend Rstudio's Viewer as a viable solution.
To continue with #Joseph Clark John's recommendation, using the variety of other devices R offers might be of use to you. Their recommendation to use x11() is specific to linux distributions so if using Windows or MacOs, you could produce another window using the windows() or quartz() commands, respectively (See documentation for all relevant devices).
This post touches on this:
Make R Studio plots only show up in new window
Alternatively, you could use plotly::ggplotly() to display a ggplot in the Viewer pane:
library(ggplot2)
library(plotly)
data(iris)
plotObj <- ggplot(data = iris, aes(Petal.Length)) + geom_histogram()
plotly::ggplotly(plotObj)
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
As a part of my dissertation research, I wrote R code that performs a basic exploratory data analysis (EDA) of initial datasets. The code is supposed to output the results of EDA in three formats: 1) screen (RStudio Plots window); 2) SVG files (single file per plot); 3) PDF file (one file for all univariate EDA plots and another one for all multivariate EDA plots). It is still a work in progress in terms of covering all variables of interest and their relationships, but the basic infrastructure has already been designed and implemented (using ggplot2 and gridExtra packages). I am experiencing the following two issues with this:
1) When, during EDA, the code is supposed to display a current plot in the RStudio Plots window, the screen just blinks and no output is performed. The following is the code that generates and displays plots (screen and SVG only, see below for PDF output) [similar blocks of code are wrapped in functions, returning plot objects (g), which form a list, which, in turn, is passed to lapply() for iterating through all plots]:
df$var <- factor(df[[colName]])
title <- paste("Projects distribution across", colName, "range")
g <- ggplot(data=df, aes(x=var, fill=var)) +
geom_bar(stat="bin") +
scale_fill_discrete(colName) +
xlab(colName) +
ylab("Number of projects") +
ggtitle(label=title)
if (.Platform$GUI == "RStudio") {print(g); dev.off()}
edaFile <- str_replace_all(string=colName, pattern=" ", repl="")
edaFile <- paste0(EDA_RESULTS_DIR, "/", edaFile, ".svg")
suppressMessages(ggsave(file=edaFile, plot=g))
2) After attempting to open PDF file with EDA results, it opens, but further attempts to navigate it (i.e., line or page scrolling) or otherwise work with it (i.e., change zoom level) result in hanging of a PDF reader program (Adobe Reader XI) with message in its title bar "... (Not Responding)". Sometimes, after quite a while, Adobe Reader returns back to the responsive state, but for a short period of time, until next action sends its again to the hanging state. I noticed that it takes time for Adobe Reader to display one particular plot, specifically a Q-Q plot. Just wanted to mention this, as it might give additional insight. The following is the code that outputs saved plots to a PDF file (these are the same plots that were saved and displayed on the screen as well as were output to SVG files, as described above):
edaFilePDF <- paste0(EDA_RESULTS_DIR, "/", "eda-univar.pdf")
mg <- do.call(marrangeGrob, c(allPlots, list(nrow=2, ncol = 1)));
suppressMessages(ggsave(filename=edaFilePDF, mg, width=8.5, height=11))
Your help is much appreciated! P.S. I use RStudio Server, so the output is browser-based.
I am generating and saving an EMF file with ggplot2 and with the win.graph command. the output graph is low quality and lines looked jagged. I really need to have it in EMF format (exporting to pdf solves the problem but I need the EMF file). How can I make it high quality? (the emf output is here in case you like to see it)
require(ggplot2)
my.dates = as.Date(c("2011-07-22","2011-07-23",
"2011-07-24","2011-07-28","2011-07-29"))
my.vals = c(5,6,8,7,3)
my.data <- data.frame(date =my.dates, vals = my.vals)
plot(my.dates, my.vals)
p <- ggplot(data = my.data, aes(date,vals))+ geom_line(size = 1.5)
p <- p + scale_x_date(format="%m/%d", ' ')
win.graph(width=860/72, height=450/72,pointsize = 12)
print(p)
savePlot("c:/test.emf",type="emf")
dev.off()
EMF is vector based. I was pasting the EMF files into powerpoint slides and I noticed that they are rendered as low res. If you right click on the EMF file and select edit photo it will render it properly. That solved my problem.
Update:
I went ahead and wrote a little VBA script that ungroups the EMF file. It breaks it into a graph object that can be easily scaled. It looks very nice now.
You can save your ggplot as SVG and then post-process it with Inkscape.
It's easy to use, free and gives great results.