ggplot's qplot does not execute on sourcing
Update:
- .R files:
source
's optionprint.eval=TRUE
will lead to printing behaviour of the evaluation result like in the interactive command line.
source("Script.R", print.eval=TRUE)
- .Rnw files:
knitr
by default emulates the behaviour of the interactive command line wrt.print
ing. Note thatknitr
can be specified as Sweaving engine also for R package vignettes.
This is my original answer. But note that this workaround is IMHO completely obsolete now (and it always was good for a small lazy niche only).
This is the famous FAQ 7.22: Why do lattice/trellis graphics not work?.
For grid graphics like ggplot2 or lattice, you need to print the graphics object in order to actually draw it.
Interactively on the command line this is done automatically. Everywhere else (inside files to be sourced, loops, functions, Sweave chunks) you need to print it explicitly.
print (qplot (1 : 10, 1 : 10))
Alternatively, you can redefine qplot
to do the printing:
qplot <- function (x, y = NULL, z = NULL, ...) {
p <- ggplot2::qplot (x = x, y = y, z = z, ...)
print (p)
}
(this changes the axis labels to x and y).
I use this approach in vignettes where I want to write code exactly as a user in an interactive session would type it.
ggplot2 does not appear to work when inside a function R
It's an R FAQ -- you need print()
around it, or a ggsave()
which is particular to ggplot2.
From the FAQ:
7.22 Why do lattice/trellis graphics not work?
The most likely reason is that you forgot to tell R to display the
graph. Lattice functions such asxyplot()
create a graph object, but
do not display it (the same is true of ggplot2 graphics, and Trellis
graphics in S-Plus). Theprint()
method for the graph object produces
the actual display. When you use these functions interactively at the
command line, the result is automatically printed, but insource()
or
inside your own functions you will need an explicitprint()
statement.
Ggplot does not show plots in sourced function
I'll preface this by saying that the following is bad practice. It's considered bad practice to break a programming language's scoping rules for something as trivial as this, but here's how it's done anyway.
So within the body of your function you'll create both plots and put them into variables. Then you'll use ggsave()
to write them out. Finally, you'll use assign()
to push the variables to the global scope.
library(ggplot2)
myFun <- function() {
#some sample data that you should be passing into the function via arguments
df <- data.frame(x=1:10, y1=1:10, y2=10:1)
p1 <- ggplot(df, aes(x=x, y=y1))+geom_point()
p2 <- ggplot(df, aes(x=x, y=y2))+geom_point()
ggsave('p1.jpg', p1)
ggsave('p2.jpg', p2)
assign('p1', p1, envir=.GlobalEnv)
assign('p2', p2, envir=.GlobalEnv)
return()
}
Now, when you run myFun()
it will write out your two plots to .jpg files, and also drop the plots into your global environment so that you can just run p1
or p2
on the console and they'll appear in RStudio's Plot pane.
ONCE AGAIN, THIS IS BAD PRACTICE
Good practice would be to not worry about the fact that they're not popping up in RStudio. They wrote out to files, and you know they did, so go look at them there.
ddply and ggplot - generating no plot
return(p)
in your script doesn't return a plot. p
refers to each subset of the data frame qq
. In general, to 'return' plots produced by ggplot
inside functions you need to use print
(see FAQ 7.22). However, in your particular case, where you want to save plots, you don't need print
.
Several PDF files
If you want one file per level of 'SIC', you may try something like this. d_ply
is useful when you call a function only for its side effects, like here when we save the output from a plot. Instead of pdf
/some-plotting
/dev.off
, you may use ggsave
.
d_ply(qq, .(SIC), function(p){
ggplot(p, aes(x = AVGAT, y = ADA, color = NLEAD)) + geom_point(shape = 1)
ggsave(file = paste0(unique(p$SIC), ".pdf"))
})
One PDF file with several pages
If you want one PDF file, with one page per level of 'SIC', you may use base
function pdf
, and the .print = TRUE
argument in d_ply
.
# create a new SIC variable with two levels, for a more realistic test of the function
qq$SIC2 <- rep(c(50, 100), each = 10)
pdf(file = "aaa.pdf")
d_ply(qq, .(SIC2), .print = TRUE, function(p){
ggplot(p, aes(x = AVGAT, y = ADA, color = NLEAD)) + geom_point(shape = 1)
})
dev.off()
No output from ggplot when running as a script
Try print the plot if you are calling it from another function or in Shiny:
myplot <- ggplot(data, aes(x = X, y = Y, group = group)) + geom_point()
print(myplot)
ggplot plots in scripts do not display in Rstudio
I recently happened on this question and realized that the most up to date way is to call show(p)
after creating the plot.
Why does this ggplot2 graph fail to plot when looped over?
You have to print it: print(ggplot(...))
Using ggplot2 why does changing the color palette result in all grey?
The problem comes from the fact that for some reason, palette.colors
returns a named vector when you use palette = "Okabe-Ito"
Compare the output here
palette.colors(n = 8,palette = "R4")
# [1] "#000000" "#DF536B" "#61D04F" "#2297E6" "#28E2E5" "#CD0BBC"
# [7] "#F5C710" "#9E9E9E"
palette.colors(n = 8,palette = "Okabe-Ito")
# black orange skyblue bluishgreen
# "#000000" "#E69F00" "#56B4E9" "#009E73"
# yellow blue vermillion reddishpurple
# "#F0E442" "#0072B2" "#D55E00" "#CC79A7"
When you use scale_fill_manual(values=)
, if you pass a named vector, then it will try to match up the names of in the color vector to the names of the levels of your factor. Since your Source
values are "Repeatability" and "Reproducibility" and not values like "orange" and "skyblue", the matching doesn't work and you just get grey. If you remove the names, then it won't try to do the matching.
color <- unname(palette.colors(n = 8, palette = "Okabe-Ito"))
should work
Related Topics
Add Count of Unique/Distinct Values by Group to the Original Data
Replace Missing Values (Na) With Most Recent Non-Na by Group
How to Specifically Order Ggplot2 X Axis Instead of Alphabetical Order
Show Percent % Instead of Counts in Charts of Categorical Variables
Why Are My Dplyr Group_By & Summarize Not Working Properly? (Name-Collision With Plyr)
How to Set Limits For Axes in Ggplot2 R Plots
Error in ≪My Code≫: Object of Type 'Closure' Is Not Subsettable
Drop Data Frame Columns by Name
Convert a List to a Data Frame
Left Align Two Graph Edges (Ggplot)
Gather Multiple Sets of Columns
Linear Regression and Group by in R
Does Ifelse Really Calculate Both of Its Vectors Every Time? Is It Slow
How to Remove All Duplicates So That None Are Left in a Data Frame
How to Save a Plot as Image on the Disk