I have a plot as shown below. To this plot i would like to add a similar kind of line plot somewhere within the plot (bottomright or bottomleft). The command for the subplot i am using is
plot( 1:121, sample(1:121),type='l' )
It plots right on the top of the first one. I need it as a small plot either at the bottomleft or bottomright. COuld someone help to do this in R?
op <- par(no.readonly = TRUE)
set.seed(42)
plot(rnorm(100), runif(100))
par(new=TRUE, oma=c(3,1,1,2))
layout(matrix(1:4,2))
plot(rnorm(100), runif(100), col="blue", xlab="", ylab="")
par(op)
If you set the parameter new to TRUE, the canvas will not be cleaned before the next plotting command:
par( new= TRUE )
I leave it to your ingenuity to create a suitable white background and position the new plot :-) Hint: take a look at the omd parameter in the manual for par.
Related
If you call function hist on r, you will note that the box that usually surrounds plotting region doesn't appear, instead, only rulers indicating plot scale appear on the bottom and on the left. If you use r a lot you may probably have noticed this already. my question is: there is some graphical parameter or workaround to make this happen on any other plot of basic r (like in a scatterplot, a line plot, a qq plot or whatever)?
The only parameter I found was axes, but setting it to FALSE makes it disappear not only the box, but also the rulers.
You are looking for box().
op <- par(mfrow=c(1, 2))
hist(mtcars$mpg, sub="w/o box")
hist(mtcars$mpg, sub="w/ box")
box() ## <-- this
par(op)
the answer is bty graphical parameter:
x= matrix(rnorm(100), ncol= 2)
plot(x, bty= 'n')
I'm doing stochastic dominance analysis with diferent income distributions using Pen's Parade. I can plot a single Pen's Parade using Pen function from ineq package, but I need a visual comparison and I want multiple lines in the same image. I don't know how extract values from the function, so I can't do this.
I have the following reproducible example:
set.seed(123)
x <- rnorm(100)
y <- rnorm(100, mean = 0.2)
library(ineq)
Pen(x)
Pen(y)
I obtain the following plots:
I want obtain sometime as the following:
You can use add = TRUE:
set.seed(123)
x <- rnorm(100)
y <- rnorm(100, mean = 0.2)
library(ineq)
Pen(x); Pen(y, add = TRUE)
From help("Pen"):
add logical. Should the plot be added to an existing plot?
While the solution mentioned by M-M in the comments is a more general solution, in this specific case it produces a busy Y axis:
Pen(x)
par(new = TRUE)
Pen(y)
I would generalize the advice for plotting functions in this way:
Check the plotting function's help file. If it has an add argument, use that.
Otherwise, use the par(new = TRUE) technique
Update
As M-M helpfully mentions in the comments, their more general solution will not produce a busy Y axis if you manually suppress the Y axis on the second plot:
Pen(x)
par(new = TRUE)
Pen(y, yaxt = "n")
Looking at ?ineq::Pen() it seems to work like plot(); therefore, followings work for you.
Pen(x)
Pen(y, add=T)
Note: However, add=T cuts out part of your data since second plot has points which fall out of the limit of the first.
Update on using par(new=T):
Using par(new=T) basically means overlaying two plots on top of each other; hence, it is important to make them with the same scale. We can achieve that by setting the same axis limits. That said, while using add=T argument it is desired to set limits of the axis to not loose any part of data. This is the best practice for overlaying two plots.
Pen(x, ylim=c(0,38), xlim=c(0,1))
par(new=T)
Pen(y, col="red", ylim=c(0,38), xlim=c(0,1), yaxt='n', xaxt='n')
Essentially, you can do the same with add=T.
I am not an R pro, self-taught- thank you for your help!
I have figured out the following code to my satisfaction, which gives me a 3d plot of my data and I can automatically rotate it. However, I want to stop the automatic redraw of the axes as it spins. I have found many resources using par3d(skipRedraw=TRUE) but I cannot figure out how to incorporate it into my code, it is all a bit beyond me.
Also, (I was going to give up on this one but since I'm asking anyway) I'd also like to be able to have the axes labels stay next to the axis tick marks (rather than across from it/on the other side). But this is secondary.
Thank you in advance!
mydata<-read.csv(file=file.choose(),header=TRUE,row.names=1)
mydata$Colour<-factor(mydata$ColourB,levels=c("Black","Blue","Red","Green","Yellow","Purple","Brown"))
colourb<-as.character(mydata$ColourB)
library(rgl)
open3d()
plot3d(mydata[,"Sr"],
mydata[,"Rb"],
mydata[,"Zr"],
xlab="Sr (ppm)",
ylab="Rb (ppm)",
zlab="Zr (ppm)",
pch=21,
col=colourb,
type="s",
radius=10
)
bgplot3d({
plot.new()
title(main = 'Trace Elements', line = 1)
})
play3d(spin3d(axis=c(0,0,1), rpm=10), duration=10)
It is easy to stop the automatic redraw of the axes. When you use bbox-axes (default), they are redrawn. So you just use fixed position axes. (EDITED: I might misunderstand your quiestion.)
Here is my example (using data trees):
open3d()
plot3d(trees, type="s", radius=0.4, col="red", xlab="xxx", ylab="yyy", zlab="zzz",
axes=F) # not use bbox-axes
axes3d(edges = c("x","y","z")) # draw fixed position axes
box3d() # if you need, draw full box
bgplot3d({
plot.new()
title(main = 'Trees', line = 1)
})
play3d(spin3d(axis=c(0,0,1), rpm=10), duration=10)
# PS: skipRedraw isn't what you think.
plot3d(trees)
par3d(skipRedraw = T) # you can't turn the graph by drag
I'm creating a correlation heatmap in R with levelplot (lattice).
I'd like borders between the boxes, but not along the outside since it interferes with the plot border.
How can I remove the outer borders from the boxes?
Here is my code:
levelplot(matrix, border="black",
colorkey=list(height=.25, space="right", at=seq(-1, 1, .25), cuts=7),
scales=list(y=(list(cex=1)), tck = c(1,0), x=list(cex=1, rot=90)),
main="Leaf Correlations", xlab="", ylab="",
col.regions=scalebluered)
and here is what it looks like.. I don't like the double lines on the edges..
EDIT: here is a reproducible example:
data(mtcars)
cars.matrix <- as.matrix(mtcars[c(2:8)])
cars.corr <- cor(cars.matrix)
levelplot(cars.corr, border="black", colorkey=list(height=.25, space="right",
at=seq(-1, 1, .25), cuts=7),
scales=list(y=(list(cex=1)), tck = c(1,0), x=list(cex=1, rot=90)),
xlab="", ylab="")
OK, the fix for this is simple if a bit obscure.
Just use lattice.options() to reset the value of axis.padding used for factors, changing it from its default value of 0.6 (a little padding) to 0.5 (no padding), and you should be fine:
lattice.options(axis.padding=list(factor=0.5))
## An example to show that this works
data(mtcars)
cars.matrix <- as.matrix(mtcars[c(2:8)])
cars.corr <- cor(cars.matrix)
levelplot(cars.corr, border="black", colorkey=list(height=.25, space="right",
at=seq(-1, 1, .25), cuts=7),
scales=list(y=(list(cex=1)), tck = c(1,0), x=list(cex=1, rot=90)),
xlab="", ylab="")
For possibly-useful-future-reference, I figured this out by taking a quick look at the code used by prepanel.default.levelplot(). (The various prepanel.*** functions are responsible, among other things, for determining the coordinates and minimal area that should be allocated to each panel so that the objects to be plotted into it will all fit nicely.)
head(prepanel.default.levelplot, 4)
1 function (x, y, subscripts, ...)
2 {
3 pad <- lattice.getOption("axis.padding")$numeric
4 if (length(subscripts) > 0) {
A bit of digging shows that a lot of the par commands may not make it to Lattice package graphics. For example, par(bty = 'n') won't work in this levelplot example.
Unlike base R graphs, lattice graphs are not effected by many of the options set in the par( ) function. To view the options that can be changed, look at help(xyplot). It is frequently easiest to set these options within the high level plotting functions ... you can write functions that modify the rendering of panels.
Try passing the axis color directly into the graphic ala the method suggested by Yangchen Lin here: R lattice 3d plot: ticks disappear when changing panel border thickness
axis.line = list(col='transparent')
I used the information from this post to create a histogram with logarithmic scale:
Histogram with Logarithmic Scale
However, the output from plot looks nothing like the output from hist. Does anyone know how to configure the output from plot to resemble the output from hist? Thanks for the help.
A simplified, reproducible version of the linked answer is
x <- rlnorm(1000)
hx <- hist(x, plot=FALSE)
plot(hx$counts, type="h", log="y", lwd=10, lend="square")
To get the axes looking more "hist-like", replace the last line with
plot(hx$counts, type="h", log="y", lwd=10, lend="square", axes = FALSE)
Axis(side=1)
Axis(side=2)
Getting the bars to join up is going to be a nightmare using this method. I suggest using trial and error with values of lwd (in this example, 34 is somewhere close to looking right), or learning to use lattice or ggplot.
EDIT:
You can't set a border colour, because the bars aren't really rectangles – they are just fat lines. We can fake the border effect by drawing slightly thinner lines over the top. The updated code is
par(lend="square")
bordercol <- "blue"
fillcol <- "pink"
linewidth <- 24
plot(hx$counts, type="h", log="y", lwd=linewidth, col=bordercol, axes = FALSE)
lines(hx$counts, type="h", lwd=linewidth-2, col=fillcol)
Axis(side=1)
Axis(side=2)
How about using ggplot2?
x <- rnorm(1000)
qplot(x) + scale_y_log10()
But I agree with Hadley's comment on the other post that having a histogram with a log scale seems weird to me =).