R lattice histogram add the mean as text to each histogram - r

According to the previous questions answered I thought the following script should work.
require(lattice)
histogram(cyl~mpg|gear*am,
data=mtcars,
nint=5,
panel=function(y,...){
panel.histogram(...)
m<-mean(y)
panel.txt(x=30,y=60,labels=m)
}
)
The histograms plot but I'm getting the "packet 1 argument "y" is missing, with no default"
Help appreciated as I've wasted an hour of my life on this puzzle..

panel.histogram needs an x argument (not a y argument) which is a clue that this is what histogram passes to the panel.
Also, you need to pass the x argument through to panel.histogram by including it in the argument list.
Finally, it's panel.text rather than panel.txt.
histogram(cyl~mpg|gear*am,
data=mtcars,
nint=5,
panel=function(x, ...){
panel.histogram(x=x,...)
m<-mean(x)
panel.text(x=30,y=60,labels=m)
}
)

Related

Multiple histograms with title and mean as a line?

I'm struggeling with the histogram function in my exploratory analysis. I would like to run a couple of variables in my dataset through a histogram function and for each add the title and a line at the arithmetic mean. This is how far I've got (but the main title is still missing):
histo.abline <-function(x){
hist(x)
abline(v = mean(x, na.rm = TRUE), col = "blue", lwd = 4)}
sapply(dataset[c(7:10)], histo.abline)
I tried to add a main argument in the histogram function but it just doesn't pick the right variable name of my dataset vector. When I put main=x there, it says returns NULL for each variable. Colnames, names and other functions didn't work either. Could you help me?
you can try to do it with ggplot:
library(ggplot)
histo.abline <-function(dataset,colnum){
p<-ggplot(dataset,aes(dataset[,colnum]))+geom_histogram(bins=5,fill=I("blue"),col=I("red"), alpha=I(.2))+
geom_vline(xintercept = mean(dataset[,colnum], na.rm = TRUE))+xlab(as.character(names(dataset)[colnum]))
return(p)
}
since you have not provided data lets work with mtcars and create a list of histograms
dataset=mtcars
listOfHistograms<-lapply(3:7,function(x) histo.abline(dataset,x))
your list has 5 histograms that you can plot for instance the first by:
print(listOfHistograms[[1]])
More histogram options for ggplot here: https://www.r-bloggers.com/how-to-make-a-histogram-with-ggplot2/
hope this helps
EDIT: Multiple Plot in one graph
One way to do it is through cowplot library:
library(cowplot)
plot_grid(plotlist=listOfHistograms[1:4])

Change of colors in compare.matrix command in r

I'm trying to change the colors for the compare.matrix command in r, but the error is always the same:
Error in image.default(x = mids, y = mids, z = mdata, col = c(heat.colors(10)[10:1]), :
formal argument "col" matched by multiple actual arguments
My code is very simple:
compare.matrix(current,ech_b1,nbins=40)
and some of my attempts are:
compare.matrix(current,ech_b1,nbins=40,col=c(grey.colors(5)))
compare.matrix(current,ech_b1,nbins=40,col=c(grey.colors(10)[10:1]))
Assuming you're using compare.matrix() from the SDMTools package, the color arguments appear to be hard-coded into the function, so you'll need to redefine the function in order to make them flexible:
# this shows you the code in the console
SDMTools::compare.matrix
function(x,y,nbins,...){
#---- preceding code snipped ----#
suppressWarnings(image(x=mids, y=mids, z=mdata, col=c(heat.colors(10)[10:1]),...))
#overlay contours
contour(x=mids, y=mids, z=mdata, col="black", lty="solid", add=TRUE,...)
}
So you can make a new one like so, but bummer, there are two functions using the ellipsis that have a col argument predefined. If you'll only be using extra args to image() and not to contour(), this is cheap and easy.
my.compare.matrix <- function(x,y,nbins,...){
#---- preceding code snipped ----#
suppressWarnings(image(x=mids, y=mids, z=mdata,...))
#overlay contours
contour(x=mids, y=mids, z=mdata, col="black", lty="solid", add=TRUE)
}
If, however, you want to use ... for both internal calls, then the only way I know of to avoid confusion about redundant argument names is to do something like:
my.compare.matrix <- function(x,y,nbins,
image.args = list(col=c(heat.colors(10)[10:1])),
contour.args = list(col="black", lty="solid")){
#---- preceding code snipped ----#
contour.args[[x]] <- contour.args[[y]] <- image.args[[x]] <- image.args[[y]] <- mids
contour.args[[z]] <- image.args[[z]] <- mdata
suppressWarnings(do.call(image, image.args))
#overlay contours
do.call(contour, contour.args)
}
Decomposing this change: instead of ... make a named list of arguments, where the previous hard codes are now defaults. You can then change these items by renaming them in the list or adding to the list. This could be more elegant on the user side, but it gets the job done. Both of the above modifications are untested, but should get you there, and this is all prefaced by my above comment. There may be some other problem that cannot be detected by SO Samaritans because you didn't specify the package or the data.

How to create a bwplot with date on x-axis

users
thanks to the reply of #McQueenDon on r-nabble
http://r.789695.n4.nabble.com/boxplot-with-x-axis-time-td4686787.html#a4687746
I managed to produce a boxplot::base of a single variable with the x-axis correctly formatted and spaced for the date of acquisition.
What if I would like to produce it with bwplot::lattice? I need this because I would like also to use a conditional factor.
Here you are a reproducible example (thanks again to #McQueenDon )
data(iris)
pippo= stack(iris[,-5])
pippo$date= rep(c("2013/01/29", "2013/03/01", "2013/11/01",
"2013/12/01", "2014/02/01", "2014/07/02"), 100)
pippo$date= as.Date(pippo$date)
boxplot(pippo$values ~ pippo$date) ## NOT exactly what I want
bx<- boxplot(pippo$values ~ pippo$date, plot= F)
bxp(bx, at=sort(unique(pippo$date))) # this is what I was looking for !
require(lattice)
bwplot(values~date, pippo, horizontal=F) #dates looks not correctly spaced even though they are correctly ordered and formatted
# finally I would like to condition to the 'ind' variable
bwplot(values~date| ind, pippo, horizontal=F, layout= c(2,2))
Thanks
Giuseppe
How about
xyplot(values~date| ind, pippo, horizontal=F, layout= c(2,2),
panel=panel.bwplot, box.width=20)
Here we use xyplot with a custom panel= parameter rather than bwplot because bwplot converts the x to a factor first which renumbers all the levels with sequential integers; xyplot does not do this.
If you wanted to label the exact dates, you could try
dts<-unique(pippo$date)
xyplot(values~date| ind, pippo, horizontal=F, layout= c(2,2),
panel=panel.bwplot, box.width=20,
scales=list(x=list(at=dts)))
but that looks quote crowded in this particular example.

r - Add text to each lattice histogram with panel.text but has error "object x is missing"

In the following R code, I try to create 30 histograms for the variable allowed.clean by the factor zip_cpt(which has 30 levels).
For each of these histograms, I also want to add mean and sample size--they need to be calculated for each level of the factor zip_cpt. So I used panel.text to do this.
After I run this code, I had error message inside each histogram which reads "Error using packet 21..."x" is missing, with..." (I am not able to read the whole error message because they don't show up in whole). I guess there's something wrong with the object x. Is it because mean(x) and length(x) don't actually apply to the data at each level of the factor zip_cpt?
I appreciate any help!
histogram(~allowed.clean|zip_cpt,data=cpt.IC_CAB1,
type='density',
nint=100,
breaks=NULL,
layout=c(10,3),
scales= list(y=list(relation="free"),
x=list(relation="free")),
panel=function(x,...) {
mean.values <-mean(x)
sample.n <- length(x)
panel.text(lab=paste("Sample size = ",sample.n))
panel.text(lab=paste("Mean = ",mean.values))
panel.histogram(x,col="pink", ...)
panel.mathdensity(dmath=dnorm, col="black",args=list(mean=mean(x, na.rm = TRUE),sd=sd(x, na.rm = TRUE)), ...)})
A discussion I found online is helpful for adding customized text (e.g., basic statistics) on each of the histograms:
https://stat.ethz.ch/pipermail/r-help/2007-March/126842.html

How to add median vertical line to panels of lattice density plot?

I'm using a data frame in a long format to create a panelled density plot in lattice. Now I'd like to add a vertical line at the median x-value within each panel. I found a suggestion for doing it in an dotplot ( http://r.789695.n4.nabble.com/how-to-add-a-vertical-line-for-each-panel-in-a-lattice-dotplot-with-log-scale-td4632513.html ), but this doesn't work for me. Here is my code:
data(Chem97, package="mlmRev")
densityplot(~gcsescore | factor(score), data=Chem97,
panel=function(...){
panel.densityplot(...)
median.values <- median(x)
panel.abline(v=median.values, col.line="red")
})
The error is: Object x not found. So I tried the following:
panel=function(x,...){
panel.densityplot(...)
}
The moment I add x as an argument to the panel function, I get the error Error using packet 1 (2, 3 etc.). x is missing.
What's going wrong?
I've finally found the solution:
densityplot(~gcsescore | factor(score), data=Chem97,
panel=function(x,...){
panel.densityplot(x,...)
panel.abline(v=quantile(x,.5), col.line="red")
})

Resources