I can use ggplot2 to store the output of ggplot command to an object and call that object within grid.arrange to write to a file in an R script, as below:
p<-ggplot(x, aes(x=Date, y=Date)) + geom_bar(aes(x=Date,y=Data)
png("data.png", height=700, width=650)
grid.arrange(p, main=textGrob("Data"), gp=gpar(cex=2)
dev.off()
I am creating bunch of forecast graphs using plot but I cannot do the same thing. Any one has any suggestion how can I write the ouput of plot to a png file in a script?
We don't have data to work with and the questions not clear so here's an example of what I think the OP is after (separate plots for each plot) using the mtcars data set:
dat <- split(mtcars, mtcars$cyl)
lapply(dat, function(x) {
ggplot(x, aes(mpg, disp, colour=gear)) + geom_point()
}
)
#a way to get separate plots for each plot
plot2 <- function(theplot, name, ...) {
name <- paste0(name, ".png")
png(filename=name)
print(theplot)
dev.off()
} #plotting function
lapply(seq_along(dat), function(i) {
x <- dat[[i]]
z <- ggplot(x, aes(mpg, disp, colour=gear)) + geom_point()
plot2(z, name=paste0("TEST", names(dat)[i]))
}
)
data <- data.frame(x=1:10,y=rnorm(10))
p <- ggplot(data, aes(x,y)) + geom_point()
p
library(gridExtra)
Loading required package: grid
grid.arrange(p,p,p)
ggsave('~/Desktop/grid.png')
Does this approach not work with forecast graphs?
Related
So, I have a boxplot where i annotate the number of datapoint per plot and significance levels in letters above the plots. When plottet in a normal (?!?) workflow, they take about 1-2 seconds to plot in a X Window System Graphics (X11), the plot gets saved afterwards. When the plot-command is wrapped in a for-loop or called by a function, the X11-window stays empty and gets saved like that.
Here is a minimal example using mtcars, showcasing the same problem. Without context this example does not make sense.
library(ggplot2)
setwd("C:/")
output <- "C:/"
data <- mtcars
data$cyl <- as.factor(data$cyl)
#----normal plotting----
x11()
ggplot(data, aes(x = cyl, y = mpg))+
stat_boxplot(geom = "errorbar")+
geom_boxplot()
savePlot(paste0(output, "example_normal", ".tiff"), type = "tiff")
dev.off()
#----plotting throught a function----
my.plot <- function(x)
{
x11()
ggplot(x, aes(x = cyl, y = mpg))+
stat_boxplot(geom = "errorbar")+
geom_boxplot()
savePlot(paste0(output, "example_function", ".tiff"), type = "tiff")
dev.off()
}
my.plot(data)
Cheers
I had to post a print(ggplot(...)) around it to make it work in a for-loop.
I have used ggplot2 to create plot. . Here plotmodel is a function which generates individual plot based on input and i use myplot which is a list to store the plots returned by plotmodel .
for (i in 1:le) {
myplot[[i]]<-plotmodel(df2,colnames(df2)[i],z[[i]],xnames[i])
}
I have also created a single plot called "plotinfec" .
My plots work fine if I execute individually.
Can you please help or give suggestion on how can I display plotinfec and myplot in a single window .
Try this:
library(ggplot2)
library(gridExtra)
do.call(grid.arrange, c(list(plotinfec), myplot))
Example:
plotinfec <- ggplot(cars, aes(speed, dist)) + geom_density2d()
myplot <- list()
myplot[[1]] <- ggplot(cars, aes(speed, dist)) + geom_point()
myplot[[2]] <- ggplot(cars, aes(speed, dist)) + geom_hex()
myplot[[3]] <- ggplot(cars, aes(speed, dist)) + geom_line()
plotSW <- do.call(grid.arrange, c(list(plotinfec), myplot))
plot(plotSW)
I'm pretty happy with the results I'm getting with R. Most of my stacked histogram plots are looking fine, e.g.
and
However, I have a few that have so many categories in the legend that the legend is crowing out the plot, e.g.
How can I fix this?
Here is my plot.r, which I call on the command line like this
RScript plot.r foo.dat foo.png 1600 800
foo.dat
account,operation,call_count,day
cal3510,foo-method,1,2016-10-01
cra4617,foo-method,1,2016-10-03
cus4404,foo-method,1,2016-10-03
hin4510,foo-method,1,2016-10-03
mas4484,foo-method,1,2016-10-04
...
entirety of foo.dat: http://pastebin.com/xnJtJSrU
plot.r
library(ggplot2)
library(scales)
args<-commandArgs(TRUE)
filename<-args[1]
png_filename<-args[2]
wide<-as.numeric(args[3])
high<-as.numeric(args[4])
print(wide)
print(high)
print(filename)
print(png_filename)
dat = read.csv(filename)
dat$account = as.character(dat$account)
dat$operation = as.character(dat$operation)
dat$call_count = as.integer(dat$call_count)
dat$day = as.Date(dat$day)
png(png_filename,width=wide,height=high)
p <- ggplot(dat, aes(x=day, y=call_count, fill=account))
p <- p + geom_histogram(stat="identity")
p <- p + scale_x_date(labels=date_format("%b-%Y"), limits=as.Date(c('2016-10-01','2017-01-01')))
print(p)
dev.off()
Answer from #PierreLafortune
using:
p <- p + theme(legend.position="bottom")
p <- p + guides(fill=guide_legend(nrow=5, byrow=TRUE))
I am a beginner trying to build a multiple plots in ggplot2. Using the mtcars dataset in R
library(datasets)
data (mtcars)
library (ggplot2)
## convert to factor some variables to avoid problems
factors<-c(2,9,10,11)
mtcars[,factors]<-lapply(mtcars[,factors],factor)
I want to plot mpg vs all the other variables except the am variable that is plot in colour in each plot. Each plot looks like this:
g1<- ggplot(mtcars, aes(x=mpg, y=cyl, color=am)) + geom_point(shape=1)
g2<- ggplot(mtcars, aes(x=mpg, y=disp, color=am)) + geom_point(shape=1)
g3...
Only the y axis changes from one plot to the other. I have done the plots form g1 to g9, y axis being any of the following:
variables<- c ("cyl","disp","hp","drat","wt","qsec","vs","gear","carb")
I am sure there must be a more elegant way to generate all 9 plots, but cannot figure out
Any help?
If you want the plots in g1...g_n:
g <- lapply(variables, function(var) {
ggplot(mtcars, aes_string(x="mpg", y=var, color="am")) + geom_point(shape=1)
})
names(g) <- paste0("g", seq(g))
list2env(g, .GlobalEnv)
I'm generating pdf reports using ggplot2. Code looks something like this
pdf()
for (){
p <- ggplot(..)
print(p)
}
dev.off()
Sometimes because of the data quality ggplot fails to generate the plot. There could be multiple reasons, and we don't want to check all possible combinations for data failing. We simply want to check if ggplot fails - and continue. This is what I came up with - this works, but there are some issues.
library(ggplot2)
p <- ggplot(mtcars, aes(wt, mpg)) +
geom_point()
p.bad <- ggplot(mtcars, aes(wt, as.character(mpg))) +
geom_point() +
scale_y_continuous()
pdf()
a <- try(print(p), silent = TRUE) # double printing
if (class(a)!='try-error'){
print(p)
}
b <- try(print(p.bad), silent = TRUE)
if (class(b)!='try-error'){
print(p.bad)
}
dev.off()
try(print) - generates a chart if there is no error. Is there a way of preventing it? This will probably the best solution. If we do the following - there is no double printing, but second try(print) generates blank page.
pdf()
a <- try(print(p), silent = TRUE)
b <- try(print(p.bad), silent = TRUE)
dev.off()
Is there another way of finding out if ggplot will generate an error?
I suggest to use ggsave:
ttt <- function() {
require(ggplot2)
p.bad <- ggplot(mtcars, aes(wt, as.character(mpg))) +
geom_point() +
scale_y_continuous()
a <- try(ggsave("test.pdf",p.bad))
return("test")
}
ttt()
# Saving 12.9 x 9.58 in image
# Error : Discrete value supplied to continuous scale
# [1] "test"