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')
Related
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
In R I often add legends to my plots like this
legend("topright",c("a=1","b=1"),lwd=c(1,2))
However, what I want to do is produce a plot which contains nothing but that legend. How do I do it? (Preferably without using package such as ggplot)
You can generate a new, empty plot frame using frame() or plot.new()
plot.new()
legend("topright",c("a=1","b=1"),lwd=c(1,2))
Use the type='n' parameter as in:
plot(x,y,type='n')
See ?plot.default for details. If you will want to add some text/points/lines to the plot afterward you may want to provide the x and y parameters, and/or the ylim and xlim parameters in order to set up the plotting region.
You can also drop the axes with the argument axes=F, and you can set the xlab,ylab, and main to NA, if you really want a blank plot.
I would like to highlight certain points (without the adjacent lines) in an ecdf plot. The problem is, that either
a) using col, the lines left of these points get labelled as well:
b) using bg has absolutely no effect even if specifying a pch that normally uses bg:
Where is my mistake? Is there an easy way to do that (other then to extract the ecdf function data and create the plot by hand)? I prefer plain plotting over ggplot etc. Thanks in advance!
set.seed(seed=123)
dta=rnorm(20)
plot(1:2, pch=c(19, 25), col="blue", bg="red", cex=5, lwd=4)
# works perfectly (note: pch=19 only has col, no bg, whereas others (e.g. 25) have col (border) and bg (fill))
# a)
plot(ecdf(dta), pch=19, col=c("gray","red"))
# colored symbols AND lines, but I only want to color the symbols (see 1st figure above)
# b)
plot(ecdf(dta), pch=25, col="gray",bg="red")
# specifying bg does not work from plot.ecdf (see 2nd fig. above)
Would this work for you?
set.seed(seed=123)
dta=rnorm(20)
##
plot(ecdf(dta), pch=19,
col="gray",
col.01line = "gray")
lines(ecdf(dta),col="gray",
col.points=c(
rep(c("gray","red"),20)))
##
EDIT: even easier (without the additional lines call) incorporating at the aditional parameters available for plot.stepfun directly:
# nonsense colors, just to illustrate the possibility to set further parameters:
? plot.stepfun # has many more parameters!!
plot(ecdf(dta), pch=19,
col="blue",
col.points=c(
rep(c("gray","red"),20)),
verticals=TRUE, col.vert="pink",
col.01line = "green")
I want to plot a centered legend outside of the plotting area in a device having multiple plots. There has been many questions (with slight variations) asked in SO about changing the position of legend in a R plot.
For example:
1) R - Common title and legend for combined plots
2) Common legend for multiple plots in R
3) Plot a legend outside of the plotting area in base graphics?
etc.
Now what I understood from the above questions is that I got to set the option xpd = T or xpd = NAto plot legends at the outer margins. However when I try this, it somehow does not work for me ..
par(mfrow=c(1,2),oma=c(0,3,0,0),xpd=TRUE)
plot(c(5,10),col=c("red","blue"),pch=20,cex=2,bty="n",xlab="",ylab="")
barplot(c(5,10),col=c("red","blue"))
mtext(text="My two plots",side=3,cex=2,outer=TRUE,line=-3)
legend("top",legend=c("A", "B"),fill=c("red","blue"),ncol=2,xpd=NA,bty="n") # Option 1
legend(x=0.01,y=11,legend=c("A", "B"),fill=c("red","blue"),ncol=2,xpd=TRUE,bty="n") # Option 2
Now my question is, how does xpd exactly work ? as I am unable to figure out why shouldn't the legend not be placed outside the plot area with xpd=T.
I apologize in advance if some consider this as a duplicate of the above questions !!
Help is much appreciated
Ashwin
Option #1 is likely the route you should take, with xpd=NA. It does not automatically place the legend in the outer margins, but it allows you to place the legend anywhere you want. So, for example, you could use this code to place the legend at the top of the page, approximately centered.
legend(x=-1.6, y=11.6, legend=c("A", "B"), fill=c("red", "blue"), ncol=2, xpd=NA, bty="n")
I chose these x and y values by trial and error. But, you could define a function that overlays a single (invisible) plot on top of the ones you created. Then you can use legend("top", ...). For example
reset <- function() {
par(mfrow=c(1, 1), oma=rep(0, 4), mar=rep(0, 4), new=TRUE)
plot(0:1, 0:1, type="n", xlab="", ylab="", axes=FALSE)
}
reset()
legend("top", legend=c("A", "B"), fill=c("red", "blue"), ncol=2, bty="n")
I also had a hard time to get coordinates on the margins. I think I found a solution, you can specify coordinates for the legend using:
getCoords() function.
Look also to legend_margin function from plotfunctions package.
So combining the solution from Jean V. Adams with one of these functions should get you there.
Hope that works :)
This is a basic question but I am unable to find an answer. I am generating about 9 barplots within one panel and each barplot has about 12 bars. I am providing all the 12 labels in my input but R is naming only alternate bars. This is obviously due to to some default setting in R which needs to be changed but I am unable to find it.
You may be able get all of the labels to appear if you use las=2 inside the plot() call. This argument and the others mentioned below are described in ?par which sets the graphical parameters for plotting devices. That rotates the text 90 degrees. Otherwise, you will need to use xaxt="n" (to suppress ticks and labels) and then put the labels in with a separate call to axis(1, at= <some numerical vector>, labels=<some character vector>).
# midpts <- barplot( ... ) # assign result to named object
axis(1, at = midpts, labels=names(DD), cex.axis=0.7) # shrinks axis labels
Another method is to first collect the midpoints and then use text() with xpd=TRUE to allow text to appear outside the plot area and srt be some angle for text rotation as named arguments to control the degree of text rotation:
text(x=midpts, y=-2, names(DD), cex=0.8, srt=45, xpd=TRUE)
The y-value needs to be chosen using the coordinates in the plotted area.
Copying a useful comment: For future readers who don't know what these arguments do: las=2 rotates the labels counterclockwise by 90 degrees. furthermore, if you need to reduce the font you can use cex.names=.5 to shrink the size down
To get rotated labels on a base R barplot, you could (like I do here) adapt one of the
examples given in the vignette of the gridBase package:
library(grid)
library(gridBase)
## Make some data with names long enough that barplot won't print them all
DD <- table(rpois(100, lambda=5))
names(DD) <- paste("long", names(DD), sep="_")
## Plot, but suppress the labels
midpts <- barplot(DD, col=rainbow(20), names.arg="")
## Use grid to add the labels
vps <- baseViewports()
pushViewport(vps$inner, vps$figure, vps$plot)
grid.text(names(DD),
x = unit(midpts, "native"), y=unit(-1, "lines"),
just="right", rot=50)
popViewport(3)
R won't label every bar if the labels are too big.
I would suggest trying to rotate the labels vertically by passing in the las=2 argument to your plotting function.
If the labels are still too large, you can try shrinking the font by using the cex.names=.5 argument.
Sample Data for plot
sample_curve <- c(2.31,2.34,2.37,2.52,2.69,2.81,2.83,2.85,2.94, 3.03, 3.21, 3.33) # create a sample curve
names(sample_curve)<-c("1 MO","2 MO","3 MO","6 MO","1 YR","2 YR","3 YR","5 YR","7 YR","10 YR","20 YR","30 YR") # label the curve
Example of plot with labels too big
barplot(sample_curve) # labels too big for the plot
Example of plot with labels rotated and small
barplot(sample_curve, las=2, cex.names=.5) # lables are rotated and smaller, so they fit
before plotting the barplot()
You can simply increase the margins with par() and your margins values (your plot has 4 margins) mar = c(v1,v2,v3,V4)
par(mar=c(10,4,4,4))
as example :
par(mar=c(10,4,4,4))
barplot(height=c(1,5,8,19,7),
names.arg=c("very long label 1","very long label 2",
"very long label 3","very long label 4",
"very long label 5"), las=2 )