I'm doing a linear fitting on many datasets in a loop and plotting the results in a pdf file. Is it possible to directly save the output of summary(fit) in the same pdf file instead of observing the summaries of about 100 datasets through the console?
LMmodel <- y ~ x
fit <- lm(LMmodel, data = Dataset)
pdf(file = OutputFile, width = 10, height = 6, paper = "a4r")
xLim = range(x)
yLim = range(y)
plot(x, y, type = "p", xlim = xLim, ylim = yLim,
main = plotTitle, xlab = "x [m]", ylab = "y [dB]",
pch = 20, cex = .9)
regLine(fit, col=palette()[2], lwd=2, lty=1)
grid(lwd = 1.5)
plot(density(residuals(fit)), main = "Density Plot of the Residuals"))
dev.off()
graphics.off()
return(summary(fit))
I really recommend Knitr with Rstudio to generate Report.
Here I use you code to generate a pdf in 3 simple steps. I assume you have Rstudio installed.
I create a new R sweave file ( using the menu)
Where I insert 2 chuncks (using the Chunks at right)
<<myplot,echo=FALSE,fig=TRUE>>=
library(car)
x <- rnorm(n=20,mean=30,sd=20)
y <- rnorm(n=20,mean=180,sd=10)
Dataset <- data.frame(x=x,y=y)
LMmodel <- y ~ x
fit <- lm(LMmodel, data = Dataset)
xLim = range(x)
yLim = range(y)
plot(x, y, type = "p", xlim = xLim, ylim = yLim,
main = "plotTitle", xlab = "x [m]", ylab = "y [dB]",
pch = 20, cex = .9)
regLine(fit, col=palette()[2], lwd=2, lty=1)
grid(lwd = 1.5)
plot(density(residuals(fit)), main = "Density Plot of the Residuals")
#
the summary is :
<<mysummary>>=
print(summary(fit))
#
You generate a pdf file using the compile PDF button.
You can insert what you want between the summary and the plots to build complex reports.
Related
I am planning to reproduce the attached figure, but I have no clue how to do so:
Let´s say I would be using the CO2 example dataset, and I would like to plot the relative change of the Uptake according to the Treatment. Instead of having the three variables in the example figure, I would like to show the different Plants grouped for each day/Type.
So far, I managed only to get this bit of code, but this is far away from what it should look like.
aov1 <- aov(CO2$uptake~CO2$Type+CO2$Treatment+CO2$Plant)
plot(TukeyHSD(aov1, conf.level=.95))
Axes should be switched, and I would like to add statistical significant changes indicated with letters or stars.
You can do this by building it in base R - this should get you started. See comments in code for each step, and I suggest running it line by line to see what's being done to customize for your specifications:
Set up data
# Run model
aov1 <- aov(CO2$uptake ~ CO2$Type + CO2$Treatment + CO2$Plant)
# Organize plot data
aov_plotdata <- data.frame(coef(aov1), confint(aov1))[-1,] # remove intercept
aov_plotdata$coef_label <- LETTERS[1:nrow(aov_plotdata)] # Example labels
Build plot
#set up plot elements
xvals <- 1:nrow(aov_plotdata)
yvals <- range(aov_plotdata[,2:3])
# Build plot
plot(x = range(xvals), y = yvals, type = 'n', axes = FALSE, xlab = '', ylab = '') # set up blank plot
points(x = xvals, y = aov_plotdata[,1], pch = 19, col = xvals) # add in point estimate
segments(x0 = xvals, y0 = aov_plotdata[,2], y1 = aov_plotdata[,3], lty = 1, col = xvals) # add in 95% CI lines
axis(1, at = xvals, label = aov_plotdata$coef_label) # add in x axis
axis(2, at = seq(floor(min(yvals)), ceiling(max(yvals)), 10)) # add in y axis
segments(x0=min(xvals), x1 = max(xvals), y0=0, lty = 2) #add in midline
legend(x = max(xvals)-2, y = max(yvals), aov_plotdata$coef_label, bty = "n", # add in legend
pch = 19,col = xvals, ncol = 2)
I have model created by train function from caret. I want to plot this object and increase size of text and title of axis. I found how to change size of titles, but I couldn't find how to do it for text on the axis. Example code for my problem below:
library(caret)
m <- train(mpg~., data = mtcars, tuneGrid = expand.grid(.mtry=c(2,4,5)))
plot(m, xlab = list(font=3, cex = 5), ylab = list(font=3, cex = 5))
I tried using cex.axis and ps parameters but none of them worked.
Adding the scales argument with a list for the x and y axes works for me. The items in the list for scales would be able to be customized like the axis labels were.
library(caret)
m <- train(mpg~., data = mtcars, tuneGrid = expand.grid(.mtry=c(2,4,5)))
plot(m, xlab = list(font=3, cex = 5),
ylab = list(font=3, cex = 5),
scales = list(x = list(font=2,cex=2),y=list(font=2,cex=2))
)
I am trying to prepare a graph for a poster presentation, but am getting very frustrated by how difficult things that should be simple are in plot. I want to plot a qq-plot of residuals from a mixed-effects model. All I want to do is change the font size of the axis title
. Here's a reproducible example.
library(lme4)
library(lattice)
fm1 <- lmer(Reaction ~ Days + (Days | Subject), sleepstudy)
qqmath(fm1,
main = list("QQ-Plot", cex = 2),
id=0.05,
cex = list(x = 2),
scales = list(x = list(cex = 2), y = list(cex = 2)))
This all works fine. But when I try to increase the font size of the axis title
qqmath(fm1,
main = list("QQ-Plot", cex = 2),
xlab = list("x-axis", cex = 2),
id=0.05,
cex = list(x = 2),
scales = list(x = list(cex = 2), y = list(cex = 2)))
I get
Error in qqmath.formula(x = ~x, ylab = "Standardized residuals", xlab = "Standard normal quantiles", :
formal argument "xlab" matched by multiple actual arguments
I gather from this post that this is due to competing arguments in the function call and some ellipsis in the original qqmath.formula object, but surely there has to be an easier way to set the fontsize of the axis titles than reprogramming the original function?!
The lattice system has functions trellis.par.get and trellis.par.set and this can be used to control the fontsize of the xlab and ylab components:
?trellis.par.get
names( trellis.par.get() )
trellis.par.set(par.ylab.text=list(cex=.5))
qqmath(fm1,
main = list("QQ-Plot", cex = 2), id=0.05,
cex=list(left=.55,bottom=.5),
scales = list(x = list(cex = 1), y = list(cex = 1)))
... reduces the size of the ylab. You can find a more complete list of the components and features that can be set from a chart onpage 127 in the "Lattice" book by Sarkar.
I'm currently trying to plot the components found via EM algorithm. However, the estimated densities do not extend fully to the end. It looks like this:
My code is:
plot(EM_data, which=2, xlim= c(0, 80), xlab2= "", yaxt= "n", main2 ="", lwd2=0.8, border = "azure3")
lines(density(EM_data), lty=2, lwd=0.8)
The plot is truncated wether I specify xlim or not. xlim2 is not defined for this type of plot. Where am I going wrong?
The method to plot mixEM only draws within the range of the data, if you want to extend the densities you must build your own function.
Use something like this:
Example data:
library(mixtools)
data(faithful)
attach(faithful)
set.seed(100)
EM_data<-normalmixEM(waiting, arbvar = FALSE, epsilon = 1e-03)
mixtools plot:
plot(EM_data, which=2, xlim= c(30, 110), xlab2= "", yaxt= "n", main2 ="",
lwd2=0.8, border = "azure3")
lines(density(EM_data$x), lty=2, lwd=0.8)
Adaptation by extending densities:
a <- hist(EM_data$x, plot = FALSE)
maxy <- max(max(a$density), 0.3989 * EM_data$lambda/EM_data$sigma)
hist(EM_data$x, prob = TRUE, main = "", xlab = "", xlim= c(30, 110),
ylim = c(0, maxy), yaxt= "n", border = "azure3")
for (i in 1:ncol(EM_data$posterior)) {
curve(EM_data$lambda[i] * dnorm(x, mean = EM_data$mu[i], sd = EM_data$sigma[i]),
col = 1 + i, lwd = 0.8, add = TRUE)
}
lines(density(EM_data$x), lty=2, lwd=0.8)
I am currently using library(methylKit) to analyze methylation data and as part of this process I am performing hierarchical clustering and PCA to visualize my data. I would like to export the plots for both, however when I try to save the plots using pdf() the file is created, but the file is only ~380 bytes and it cannot be opened by Preview in Mac. My code is as follows:
For hierarchical clustering:
clustermap1 <- clusterSamples(meth,dist="correlation",method="ward",plot=TRUE)
pdf(file="ClusterMapCorrWard.pdf")
plot(clustermap1)
dev.off()
For PCA Screeplot
pdf(file="PPCAScreeplot.pdf")
xx <- barplot(project.pca.proportionvariances,
cex.names = 1,
xlab = paste("Principal component (PC), 1-",length(project.pca$sdev)),
ylab = "Proportion of variation (%)",
main = "Scree plot",
ylim = c(0,20)
)
text(xx, y = project.pca.proportionvariances,
label = round(project.pca.proportionvariances,2),
pos = 3,
cex = 0.8)
dev.off()
For PCA Pairs Plots
par(cex=1.0, cex.axis=0.8, cex.main=0.8)
pdf(file="PCAPairsplot1-6.pdf")
pairs(project.pca$x[,1:6],
col = "black",
main = "Principal components analysis bi-plot\nPCs 1-6",
pch = 16,
panel = function(x,...) {
text(project.pca$x, labels=minids, cex= 0.5, pos=3)
}
)
dev.off()
For PCA Biplots
pdf(file="PCABiplotsPC1-2.pdf")
plot(project.pca$x,
type = "n",
main = "Principal components analysis bi-plot",
xlab = paste("PC1, ", round(project.pca.proportionvariances[1], 2), "%"),
ylab = paste("PC2, ", round(project.pca.proportionvariances[2], 2), "%"))
points(project.pca$x, col="black", pch=16, cex=1)
text(project.pca$x, labels=ids, cex= 0.7, pos=3)
dev.off()
What I find confusing is that this code worked previously, and successfully outputted the appropriate plots. However, when I tried to use it on another dataset (of the same type and formatting), it stopped working and now won't work on the original data set either. Using png() is able to output the plot as well.
So where have I gone wrong?
Thanks