Incorrectly recognized math symbol from PDF in LaTeX - r

I am generating plot in R and save it as PDF with:
pdf(
file='Plots/errors.pdf',
height=4,
width=7,
onefile=TRUE,
family='Helvetica',
pointsize=12
)
# Here is my graphics
dev.off()
Somewhere inside graphics I have:
mtext(
expression(mu[H1])
)
It produces neat PDF with correctly processed greek letter µ.
Then I import this PDF in LaTeX article with:
\includegraphics[width=1\textwidth,height=0.4\textheight]{../Plots/errors.pdf}
But instead of µ sign of infinity (∞) is displayed.
Why?

For seamless integration without the encoding issues, I would look at package 'TikzDevice'. It outputs Tikz images in LaTeX format. For example:
require(tikzDevice)
setwd("/Path/To/LaTeX/Files/")
#Names of LaTeX symbols
syms <- c('alpha', 'theta', 'tau', 'beta', 'vartheta', 'pi', 'upsilon', 'gamma', 'varpi', 'phi', 'delta', 'kappa', 'rho', 'varphi', 'epsilon', 'lambda', 'varrho', 'chi', 'varepsilon', 'mu', 'sigma', 'psi', 'zeta', 'nu', 'varsigma', 'omega', 'eta', 'xi', 'Gamma', 'Lambda', 'Sigma', 'Psi', 'Delta', 'Xi', 'Upsilon', 'Omega', 'Theta', 'Pi', 'Phi')
len <- length(syms)
# random colors (red, green, blue)
r <- round(runif(len), 2)
g <- round(runif(len), 2)
b <- round(runif(len), 2)
# calculate dummy data points
x <- runif(50,1,10)
y <- x + rnorm(length(x))
fit <- lm(y ~ x)
rsq <- summary(fit)$r.squared
rsq <- signif(rsq,4)
# plot the result, will create symbol-regression.tex in the working
# directory the first time this is run it may take a long time because the
# process of calulating string widths for proper placement is
# computationally intensive, the results will get cached for the current R
# session or will get permenantly cached if you set
# options( tikzMetricsDictionary='/path/to/dictionary' ) which will be
# created if it does not exist. Also if the flag standAlone is not set to
# TRUE then a file is created which can be included with \include{}
tikz('symbolr.tex', width = 4,height = 4,pointsize = 12)
# The syntax is mar=c(bottom, left, top, right).
par(mar=c(2,2,2,2))
# plot the box and the regression line
plot(x, y, type='n', xlab='', ylab='')
box()
abline(fit)
# add the latex symbols as points
text(x, y, paste('\\color[rgb]{',r,',',g,',',b,'}{$\\',syms,'$}',sep=''))
# Display the correlation coefficient
mtext(paste("Linear model: $R^{2}=",rsq,"$" ),line=0.5)
# and the equation of the line
legend('bottom', legend = paste("$y = ", round(coef(fit)[2],3),'x +', round(coef(fit)[1],3), '$', sep=''), bty= 'n')
# Close the device
dev.off()
Then all you have to do is include the file just output from R in your LaTeX document.

Related

cannot coerce type 'closure' to vector of type 'character' rgl package

I am using the rgl package to create an interactive .html file but I am getting an error in line 42. I am fairly new to this package and can't seem to define rgl_init function in line 44, so any help will be appreciated. I did find a solution (R shiny error: Cannot coerce type 'closure' to vector of type 'double'), but I don't know how to implement it to this code.
#3D convex hull of the individual tree LiDAR-derived
#Import the LAS file
LAS_File <- system.file("test.las")
#Reading
library(rLiDAR)
LAS <- readLAS("D:/Summer_2019/NRS_Project/01_data/01_las_2013/test.las")
#Setup the coordinates and data subsetting
xyz <- subset(LAS[,1:3],LAS[,3] >= 1.37)
#Find the clusters
clLAS<-kmeans(xyz, 32)
#Setup the id vector
ID<-as.factor(clLAS$cluster)
#Setting the alpha
Alpha<-0.6
#Setting the plotCAS parameter
plotit=TRUE
#Setting the convex hull color
col="forestgreen"
#Combine the xyz and id
xyzID<-cbind(xyz,ID)
#Computing the volume and surface area
library(rgl)
open3d()
voumelist<-chullLiDAR3D(xyzid = xyzID, plotit = plotit, col = col, alpha = Alpha)
summary(voumelist)
#summary
#Write CSV file
write.table(voumelist, file = 'test_volume.csv', row.names=FALSE,col.names=FALSE)
write.csv(voumelist, "test_volume.csv")
#Adding plot parameters
#Adding the 3D point cloud
plot3d(xyzID[, 1:3], col = xyzID[,4], add=TRUE)
#Axis
axes3d(c("x+", "y-", "z-"))
#Grids
grid3d(side = c('x+', 'y-', 'z'), col='gray')
title3d(xlab="UTM Easting", ylab="UTM Northing", zlab = "Height", col="red")
#Scaling
aspect3d(1,1,0.7)
#Save HTML file
library(rmarkdown)
writeWebGL(dir = "D:/Summer_2019/NRS_Project/01_data/01_las_2013", filename = file.path(dir, "D:/Summer_2019/NRS_Project/01_data/01_las_2013/Test_index.html"))
#Write a copy to display in Chrome
rgl_init()
rgl.spheres(x, y, z, r = 0.2,
color = get_colors(iris$Species))
rgl_add_axes(x, y, z, show.bbox = FALSE)
# This writes a copy into temporary directory 'webGL',
# and then displays it
browseURL(
paste("D:/Summer_2019/NRS_Project/01_data/01_las_2013/Test_index.html", writeWebGL(dir=file.path(tempdir(), "D:/Summer_2019/NRS_Project/01_data/01_las_2013"),
width=500), sep="")
)

R: Output text and graphics to pdf

I'm new to R.
I want to add both descriptive statistics and a histogram to a pdf.
The following code successfully generates two histograms using ggplot2. But the describe (from psych package) functions do not appear in the pdf.
How do I include both?
library(psych)
library(foreign)
library(nnet)
library(ggplot2)
library(reshape2)
# direct output to a file
sink("C:\\Users\\jake\\Dropbox\\__iKoda\\datafiles\\OutputR.txt", append=FALSE, split=TRUE)
gc()
memory.limit()
options(max.print=1000000)
results <- read.csv("C:\\Users\\jake\\Dropbox\\__iKoda\\datafiles\\results.csv")
pdf(file="C:\\Users\\jake\\Dropbox\\__iKoda\\datafiles\\plots.pdf")
timesTrimmedComplete=processITStimes(results,"TSICompleted")
print(describe(timesTrimmedComplete$totaltimemins) )
freq=generateQplot(timesTrimmedComplete$totaltimemins,"histogram", 1)
print(freq)
timesTrimmedINComplete=processITStimes(results,"_TSIIncomplete")
print(describe(timesTrimmedINComplete$totaltimemins))
freq1=generateQplot(timesTrimmedINComplete$totaltimemins,"histogram", 1)
print(freq1)
dev.off()
########################################################################################
generateQplot<-function(dataVector, plotType, binWidthValue)
{
freq=qplot(dataVector,geom=plotType, binwidth=binWidthValue)
return(freq)
}
processITStimes<-function(resultsData, statusCode)
{
completeResults <- resultsData[grep(statusCode, resultsData$Final_Status), ]
times <- completeResults[, grep("*duration*", colnames(completeResults))]
times[is.na(times)] <- 0
times$totaltime <- rowSums( times[,2:ncol(times)] )
times$totaltimemins <-round(times$totaltime/60, digits=0)
times$rowId<-completeResults$RowId
print(statusCode);
print(describe(times$totaltimemins) )
timesTrimmed<-times[times$totaltimemins<60,]
return(timesTrimmed)
}
sink()
If you're making ggplots, you can always use ggsave(). So you'd do
ggsave(plot = freq1, filename = "freq1.pdf", device = "pdf")
You can also specify how large to make the plot (height/width/units), etc.

R Plot over London

I have some data I want to draw over the London map.
But whenever I try to run following code:
library("Hmisc")
library("lubridate")
library("maptools")
require("rworldmap")
mtl <- readShapePoly('borough/London_Borough_Excluding_MHW.shp')
data = read.csv("test.csv")
data = data[,c("Accident_Index","Longitude","Latitude","Date")]
data$Date <- as.character(data$Date)
data$Date <- gsub(' ', '', data$Date)
data$Date <- dmy(data$Date, tz='UTC')
start <- (dmy("01/01/2011", tz='UTC'))
days <- start
# pre processed matrix for incidents
# trust me you don't want to calculate
# this from scratch (Takes hours)
load('time_mat.Rdata')
# plot initial world map
plot(getMap())
da <- 1
# where the plots will be outputted
png(paste('plots/',days[da],'.png',sep=''), height=800, width=1200, bg='grey')
# plot london map
plot(mtl,col='darkgrey')
text(51.5072, 0.1275,paste("Collisions in London\n",days[da]),cex=2)
points(data$Longitude,data$Latitude, pch=20, col='white', cex=2)
par(lwd=2.5,cex=1.4)
subplot(
plot(days[1:da],incident_rate[1:da],
lwd=1.5,type='l',
ylab='', xlab='',
col='red',
ylim=c(0,max(c(1,max(incident_rate[1:da]))))
),
size=c(5.5,2), 51.5072, -0.1275, vadj=0,hadj=0
)
dev.off()
Error in par(plt = c(xy$x, xy$y), new = TRUE) :
invalid value specified for graphical parameter "plt"
EDIT 2: Re-factored and reduced the code.
Zipped up the entire code folder, and dependent data for ease of deployment/testing, ended up being ~17mb compressed (due to the shapefiles):
Megafileupload link

Adding axis titles in gplot using filled.contour in R

This is my reproducible code example. Everything looks as it should in the graph, except the axis titles/labels are not being added. I am really struggling to figure out how to fix it, despite following the directions in the function documentation. Help will be much appreciated - thanks in advance.
output <- matrix(data = c(0.7,0.5,0.3,0.8,0.6,0.4,0.9,0.7,0.5,1,0.8,0.6),nrow=3,
ncol=4)
# Change column names
colnames(output) <- c(10,20,30,40)
# Change row names
rownames(output) <- c(1,2,3)
library(gplots)
matrix.axes <- function(data) {
# Do the rows, las=2 for text perpendicular to the axis
x <- (1:dim(data)[1] - 1) / (dim(data)[1] - 1);
axis(side=1, at=x, labels=rownames(data), las=1);
# Do the columns
x <- (1:dim(data)[2] - 1) / (dim(data)[2] - 1);
axis(side=2, at=x, labels=colnames(data), las=2);
}
# Not necessary to save as pdf unless this is part of the problem
# save to pdf
# pdf("C:/Test.pdf")
# Plot results
filled.contour(output,plot.title=title(main="Method"),
xlab='Case number',ylab='Sample number',
plot.axes=matrix.axes(output))
# dev.off()
Your xlab = and ylab = need to be inside the plot.title() function:
filled.contour(output,
plot.title = title(main = "Method", xlab='Case number', ylab='Sample number'),
plot.axes = matrix.axes(output))

TikZDevice: Add \caption{} and \label{} to TikZ diagram using R

I've created a for loop that outputs several plots (via ggplot2) from R into a single .tex file using the tikzDevice package. This makes it easier to include multiple diagrams from within a latex document using a single command that points to the .tex file outputted from R (say 'diagrams.tex'): \include{diagrams}.
However, I would also like to wrap each tikzpicture with the \begin{figure} environment, so that I can insert two additional lines into each respective figure: \caption{} and \label{}.
Question: is there a way to include the figure wrapper, caption, and label latex commands directly, for each respective ggplot image (from my R loop), in the outputted .tex file?
Here is reproducible R code that generates a file 'diagrams.tex' containing 3 ggplots:
require(ggplot2)
require(tikzDevice)
## Load example data frame
A1 = as.data.frame(rbind(c(4.0,1.5,6.1),
c(4.0,5.2,3.5),
c(4.0,3.4,4.3),
c(4.0,8.2,7.3),
c(4.0,2.9,6.3),
c(6.0,3.9,6.6),
c(6.0,1.5,6.1),
c(6.0,2.7,5.3),
c(6.0,2.9,7.4),
c(6.0,3.7,6.0),
c(8.0,3.9,4.2),
c(8.0,4.1,3.5),
c(8.0,3.7,5.8),
c(8.0,2.5,7.5),
c(8.0,4.1,3.5)))
names(A1) = c("state","rmaxpay","urate")
i = 2
## name output file
tikz( 'diagrams.tex' )
for (i in 2:4){ #begin LOOP
st = i*2
df = NULL
df = subset(A1, state == st , select = c(2:3))
print( # start print
ggplot(df, aes(rmaxpay,urate)) + geom_point()
) # end print
} #end LOOP
dev.off()
There may be a way to do this with plot hooks but as it is you can do it by using the console option and sink():
require(ggplot2)
require(tikzDevice)
## Load example data frame
A1 = as.data.frame(rbind(c(4.0,1.5,6.1),
c(4.0,5.2,3.5),
c(4.0,3.4,4.3),
c(4.0,8.2,7.3),
c(4.0,2.9,6.3),
c(6.0,3.9,6.6),
c(6.0,1.5,6.1),
c(6.0,2.7,5.3),
c(6.0,2.9,7.4),
c(6.0,3.7,6.0),
c(8.0,3.9,4.2),
c(8.0,4.1,3.5),
c(8.0,3.7,5.8),
c(8.0,2.5,7.5),
c(8.0,4.1,3.5)))
names(A1) = c("state","rmaxpay","urate")
i = 2
fn <- "diagrams.tex"
if(file.exists(fn)) file.remove(fn)
for (i in 2:4){ #begin LOOP
st = i*2
df = NULL
df = subset(A1, state == st , select = c(2:3))
cat("\\begin{figure}\n", file = fn, append=TRUE)
sink(fn, append=TRUE)
tikz(console = TRUE)
print( # start print
ggplot(df, aes(rmaxpay,urate)) + geom_point()
) # end print
dev.off()
sink()
cat(paste("\\caption{figure}\\label{fig:",i,"}\n",sep=""), file = fn, append=TRUE)
cat("\\end{figure}\n", file = fn, append=TRUE)
} #end LOOP

Resources