Embedding output from ggplot into another plot [duplicate] - r

This question already has answers here:
Combined plot of ggplot2 (Not in a single Plot), using par() or layout() function? [duplicate]
(3 answers)
R: How should I create Grid-graphics?
(2 answers)
Closed 8 years ago.
I am trying to plot a scatterplot and box plot of two continuous varaibles but am getting an error that says,
Warning message:
In par(fig = c(0, 0.8, 0.55, 1), new = TRUE) :
calling par(new=TRUE) with no plot
The code worked when I simply replaced lines 4-6 of my code with:
plot(mydata$gre, mydata$gpa, xlab="GRE",ylab="GPA")
Here's my code:
mydata <- read.csv("http://www.ats.ucla.edu/stat/data/binary.csv")
par(fig=c(0,0.8,0,0.8), new=TRUE)
#plot(mydata$gre, mydata$gpa, xlab="GRE",ylab="GPA")
d<-ggplot(mydata,aes(x=mydata$gre, y=mydata$gpa))
d<-d+geom_line()
d
par(fig=c(0,0.8,0.55,1), new=TRUE)
boxplot(mydata$gre, horizontal=TRUE, axes=FALSE)
par(fig=c(0.65,1,0,0.8),new=TRUE)
boxplot(mydata$gpa, axes=FALSE)
mtext("Enhanced Scatterplot", side=3, outer=TRUE, line=-3)
Could you please shed some light on what I am doing wrong with regards to ggplot since R isn't recognizing it? What's really weird is that when I type d, the name of my ggplot, I get a plot...

You are attempting to combine grid plots (ggplot2) and base plots (boxplot), but those 2 types of plotting do not play nicely together (hence the cryptic warning).
The simplest solution is to only use one of grid or base plots by replacing the call to ggplot with a call to plot or other functions (base only option) or using grid based functions to do the boxplots (lattice package also uses grid) then use functions from the grid package to arrange the multiple plots.
If you really want to combine grid and base plots then you can use the gridBase package, but this is going to require understanding both types of graphics quite well.

Related

Back to basics: How to name a plot without ggplot in R [duplicate]

This question already has answers here:
Save a plot in an object
(4 answers)
Closed 1 year ago.
Old-school plots are the only way of plotting the exact nls model I need, so I plot a useful graph. It is, though, full of text and elements (like lines) on top since I wrote the code for each element separately. I need to be able to name my plot as one single graph/image/plot.
The code looks like this:
plot(x~y,data=df, lwd=2, col = c(1,2,3))[Generation], pch=c(15,16,17) [Generation])
axis(1,at=c(2,4, 6),cex.axis=1.6)
axis(2,at=c(0, 5, 10, 15, 20), las=1,cex.axis=1.6)
curve(vbT(x,Linf=coef(VB)),col="black",add=TRUE, lty=1)
segments(4.5,10, 4.5,0, col=rgb(0,0,1,alpha=0.8), lwd=c(1))
text(2, 10, "Group A", col=rgb(0.1,0.4,0.45, alpha=1), cex = 1, pos=1)
It has more elements, but this gives the idea. It's just longer, so the number of lines doesn't change the problem.
I tried with all kind of parentheses and arrows:
Plot1<- {My code... all the lines}
I tried plot.default and some other functions. I just can`t manage to name all of this as one "image" or plot. I am very used to ggplot now, but I must use basic r plots again. Because I am trying to graph together with some ggplots using the function ggarrange.
Thanks for your help!!!
You could use recordPlot as explained here :
df <- data.frame(x = 1:10, y = rnorm(10))
# Draw your plot
plot(y~x,data=df)
lines(rnorm(10) , col=2)
# Save your plot
p <- recordPlot()
# Do stuff
# Reuse your plot
p

How to plot multiple Dotplots in R with Hmisc package [duplicate]

This question already has answers here:
Lattice: multiple plots in one window?
(3 answers)
Closed 7 years ago.
So I've been trying to get two Dotplots (Hmisc package) to turn up in the same graph but R draws them sequentially instead.
Anybody know how to draw two Dotplots in the same graph, specifically using the Hmisc package?
I've tried somethings like
par(mfrow = c(1, 2))
Dotplot(latitude~mortality, data=USmelanoma)
Dotplot(longitude~mortality, data=USmelanoma)
But it draws them in two seperate graphs, one after the other instead of in one graph, as I had expect par(mfrow = c(1,2)) to do
You can't mix base graphics with lattice graphics which you are trying to do here (well, you can but not easily and not in the manner you are trying to do here).
One way is to use the grid.arrange() function in the gridExtra package, e.g.
## load packages required
library("HSAUR2")
library("Hmisc")
library("gridExtra")
## draw each plot separately and save to objects
plt1 <- Dotplot(latitude ~ mortality, data = USmelanoma)
plt2 <- Dotplot(longitude ~ mortality, data = USmelanoma)
## arrange the stored plots
grid.arrange(plt1, plt2, ncol = 2)
This gives:
This is an easy way to do what you want; there are other ways to do this directly with functions in the grid package itself, but they require a little more from the user.

suppress the margin of R plots vertically [duplicate]

This question already has answers here:
move subplots closer together with R
(2 answers)
Closed 9 years ago.
I am using base R plot function to generate vertically aligned plots (2-by-1), with both x and y labels but without a title. However, when I use
par(mfrow=c(2,1))
plot(obj1)
plot(obj2)
I notice that the blank margin area between the two plots is so huge (I assume R does not exclude the area for the main= title...). Is there a way to make the two plots more "closer" to each other, while keep the x-labels at appropriate locations?
BTW, is there a way to generate a plot in PDF format without any useless blank margins? I plan to include the figure in the paper manuscript, and I don't want to see such margins occupying. Thanks!
As described in the (duplicate) question I linked to, the solution is exactly the same as there:
par(mfrow=c(2,1))
par(mar = c(0,4,4,2) + 0.1)
plot(1:5)
par(mar = c(5,4,0,2) + 0.1)
plot(1:5)

colouring plot by factor using custom colours in r [duplicate]

This question already has answers here:
Colouring plot by factor in R
(6 answers)
Closed 9 years ago.
I am trying to make a scatter plot coloured by factor. I am using the following code:
data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
Is there anyway I can colour by the species factor but specify my own custom colours? Having a look around on Google it seems it is possible to do using ggplot2 but I have never used it and was hoping I could do this using the basic R functions.
Any help would be greatly appreciated!
You can manually set the R palette used by your plot call like so:
palette(c("blue","pink","green"))
Which you can reset like so:
palette("default")
Try it out, creating two plots, one with default colours, one with the new colours specified:
# default plotting
palette("default")
plot(iris$Sepal.Length, iris$Sepal.Width, col=iris$Species, pch=19)
# after specifying custom palette
palette(c("blue","pink","green"))
plot(iris$Sepal.Length, iris$Sepal.Width, col=iris$Species, pch=19)

Problem with axis limits when plotting curve over histogram [duplicate]

This question already has an answer here:
How To Avoid Density Curve Getting Cut Off In Plot
(1 answer)
Closed 6 years ago.
newbie here. I have a script to create graphs that has a bit that goes something like this:
png(Test.png)
ht=hist(step[i],20)
curve(insert_function_here,add=TRUE)
I essentially want to plot a curve of a distribution over an histogram. My problem is that the axes limits are apparently set by the histogram instead of the curve, so that the curve sometimes gets out of the Y axis limits. I have played with par("usr"), to no avail. Is there any way to set the axis limits based on the maximum values of either the histogram or the curve (or, in the alternative, of the curve only)?? In case this changes anything, this needs to be done within a for loop where multiple such graphs are plotted and within a series of subplots (par("mfrow")).
Inspired by other answers, this is what i ended up doing:
curve(insert_function_here)
boundsc=par("usr")
ht=hist(A[,1],20,plot=FALSE)
par(usr=c(boundsc[1:2],0,max(boundsc[4],max(ht$counts))))
plot(ht,add=TRUE)
It fixes the bounds based on the highest of either the curve or the histogram.
You could determine the mx <- max(curve_vector, ht$counts) and set ylim=(0, mx), but I rather doubt the code looks like that since [] is not a proper parameter passing idiom and step is not an R plotting function, but rather a model selection function. So I am guessing this is code in Matlab or some other idiom. In R, try this:
set.seed(123)
png("Test.png")
ht=hist(rpois(20,1), plot=FALSE, breaks=0:10-0.1)
# better to offset to include discrete counts that would otherwise be at boundaries
plot(round(ht$breaks), dpois( round(ht$breaks), # plot a Poisson density
mean(ht$counts*round(ht$breaks[-length(ht$breaks)]))),
ylim=c(0, max(ht$density)+.1) , type="l")
plot(ht, freq=FALSE, add=TRUE) # plot the histogram
dev.off()
You could plot the curve first, then compute the histogram with plot=FALSE, and use the plot function on the histogram object with add=TRUE to add it to the plot.
Even better would be to calculate the the highest y-value of the curve (there may be shortcuts to do this depending on the nature of the curve) and the highest bar in the histogram and give this value to the ylim argument when plotting the histogram.

Resources