Pasting value into R plot title - r

I would like to paste the value of the mean in a plot title using the title() function.
e.g. title("My plot \n mean = mean(x)")
where x is a numeric vector of observations.
I know how to do this using plot(main = " ... ", ). Simply use paste() or substitute(expression()); however, this doesn't seem work with the title() function.
Any ideas?

Answer by #MarcoSandri is correct. The correct way of using the example codes you have written are,
title(main= paste("My plot \n mean =", mean(x)))
and
avg <- mean(x)
title(paste("My Plot \n Mean = ", avg))

See this example where title works correctly:
set.seed(1)
x <- rnorm(30)
txt <- paste("Mean =", round(mean(x),3) )
plot(x)
title(main=txt)

Related

cannot change the main title and x, y labels for plot() of boot() result

I am new to R but have had some practice labelling plots so I thought this would be the same for the result from a bootstrap using boot().
#question 7
library(boot)
# function to obtain mean of x
fc <- function(x, indices){
dt <- x[indices]
c(mean(dt))
}
set.seed(123)
mybootstrap <- boot(x, fc, R=1000)
head(mybootstrap)
plot(mybootstrap, index=1,main="Boostrap mean of x", xlab="mean", ylab="density")
But actually it is giving me the generic "Histogram of t" and xlab of "t*" rather than what I wrote in the brackets to specify these things. Why is this so?
It's not easy to adjust the plot settings in boot. Best is to pull out t and use plot with freq=F to get a density plot:
hist(mybootstrap$t, freq = FALSE, breaks = 50,
main="Boostrap mean of x", xlab="mean", ylab="density")

R multi boxplot in one graph with value (quantile)

How to create multiple boxplot with value shown in R ?
Now I'm using this code
boxplot(Data_frame[ ,2] ~ Data_frame[ ,3], )
I tried to use this
boxplot(Data_frame[ ,2] ~ Data_frame[ ,3], )
text(y=fivenum(Data_frame$x), labels =fivenum(Data_frame$x), x=1.25)
But only first boxplot have value. How to show value in all boxplot in one graph.
Thank you so much!
As far as I understand your question (it is not clear how the fivenum summary should be displayed) here is one solution. It presents the summary using the top axis.
x <- data.frame(
Time = c(1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3),
Value = c(5,10,15,20,30,50,70,80,100,5,7,9,11,15,17,19,17,19,100,200,300,400,500,700,1000,200))
boxplot(x$Value ~ x$Time)
fivenums <- aggregate(x$Value, by=list(Time=x$Time), FUN=fivenum)
labels <- apply(fivenums[,-1], 1, function(x) paste(x[-1], collapse = ", "))
axis(3, at=fivenums[,1],labels=labels, las=1, col.axis="red")
Of course you can additionally play with the font size or rotation for this summary. Moreover you can break the line in one place, so the label will have smaller width.
Edit
In order to get what have you posted in the comment below you can add
text(x = 3 + 0.5, y = fivenums[3,-1], labels=fivenums[3,-1])
and you will get
however it won't be readable for other boxplots.

In R, why is there awkward output in the legend when I am using paste() instead of c() in addition to pretty10exp()?

I'm trying to make the legend of this plot pretty, so I need there the be an actual superscript, which is why I am using the pretty10exp() function from the sfsmisc library. It works when I use the c() function.
However, I am also trying to keep the string and the scientific notation number on the same line. The legend() is broken into two lines, which I think is due to c(). I thought I could use paste(), but for some reason the output is now incorrect.
plot(1:12)
pVal <- 4
legend("topright", legend = c("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)
legend("topright", legend = paste("P value:", sfsmisc::pretty10exp(pVal)), cex = 1.5)
pVal being an arbitrary number represented in scientific notation. The second line results in output like this: "P value: (significand) %*% 10^-4". The first line also doesn't give me what I want. How can I fix this problem?
pretty10exp returns an expression which allows it to use the ?plotmath features for making nice looking numbers. When working with expressions, you can't just paste values in like strings. You need to manipulate them with a special set of functions. One such function is substitute. You can do
plot(1:12)
pVal <- 4
legend("topright", cex = 1.5,
legend = substitute("P value: "*x, list(x=sfsmisc::pretty10exp(pVal)[[1]])) )
We use substitute() to take the value contained in the expression from pretty10exp and prefix it with the label you want. (We use * to concatenate rather than paste() since plotmath allows it)
This is what I would do:
fun <- function(text, pVal) {
y <- floor(log10(pVal))
x <- pVal / 10^y
bquote(.(text)*":" ~ .(x) %.% 10 ^ .(y))
}
plot.new()
text(0.5,0.7,fun("P value", 0.4))
text(0.5, 0.3, fun("P value", signif(1/pi, 1)))
No package is needed.

superpose a histogram and an xyplot

I'd like to superpose a histogram and an xyplot representing the cumulative distribution function using r's lattice package.
I've tried to accomplish this with custom panel functions, but can't seem to get it right--I'm getting hung up on one plot being univariate and one being bivariate I think.
Here's an example with the two plots I want stacked vertically:
set.seed(1)
x <- rnorm(100, 0, 1)
discrete.cdf <- function(x, decreasing=FALSE){
x <- x[order(x,decreasing=FALSE)]
result <- data.frame(rank=1:length(x),x=x)
result$cdf <- result$rank/nrow(result)
return(result)
}
my.df <- discrete.cdf(x)
chart.hist <- histogram(~x, data=my.df, xlab="")
chart.cdf <- xyplot(100*cdf~x, data=my.df, type="s",
ylab="Cumulative Percent of Total")
graphics.off()
trellis.device(width = 6, height = 8)
print(chart.hist, split = c(1,1,1,2), more = TRUE)
print(chart.cdf, split = c(1,2,1,2))
I'd like these superposed in the same frame, rather than stacked.
The following code doesn't work, nor do any of the simple variations of it that I have tried:
xyplot(cdf~x,data=cdf,
panel=function(...){
panel.xyplot(...)
panel.histogram(~x)
})
You were on the right track with your custom panel function. The trick is passing the correct arguments to the panel.- functions. For panel.histogram, this means not passing a formula and supplying an appropriate value to the breaks argument:
EDIT Proper percent values on y-axis and type of plots
xyplot(100*cdf~x,data=my.df,
panel=function(...){
panel.histogram(..., breaks = do.breaks(range(x), nint = 8),
type = "percent")
panel.xyplot(..., type = "s")
})
This answer is just a placeholder until a better answer comes.
The hist() function from the graphics package has an option called add. The following does what you want in the "classical" way:
plot( my.df$x, my.df$cdf * 100, type= "l" )
hist( my.df$x, add= T )

Using subscript and variable values at the same time in Axis titles in R

I want to use the title "CO2 emissions in wetlands" in a plot in R, whereas the 2 in CO2 is in subscript, and the value for the region (here: "wetlands") is contained in a variable named "region".
region = "wetlands"
plot (1, 1, main=expression(CO[2]~paste(" emissions in ", region)))
The problem is, that not the value of the variable is pasted, but the name of the variable. This gives "CO2 emissions in region" instead of "CO2 emissions in wetlands". I also tried:
region="wetlands"
plot (1,1,main=paste(expression(CO[2]), "emissions in", region))
But the subscript is not done here, and the title is: "CO[2] emissions in wetlands".
Is it somehow possible to get values of variables into expression?
Thanks for your help,
Sven
There is no need to use paste() in producing an expression for plothmath-style annotation. This works just fine:
region <- "foo"
plot (1, 1, main = bquote(CO[2] ~ "emissions in" ~ .(region)))
giving:
Using paste() just gets in the way.
Nb: You have to quote "in" because the parser grabs it as a key part of R syntax otherwise.
You can use substitute:
mn <- substitute(CO[2]~ "emissions in" ~ region, list(region="wetlands") )
plot(1, 1, main=mn )
From the ?substitute help file:
The typical use of substitute is to create informative labels for
data sets and plots. The myplot example below shows a simple use of
this facility. It uses the functions deparse and substitute to create
labels for a plot which are character string versions of the actual
arguments to the function myplot.
For your case, stolen from one of the answers at the duplicated link:
x <- "OberKrain"
plot(1:10, 1:10, main = bquote(paste(CO[2], " in ", .(x))))

Resources