I am trying to save plots which have female (\u2640) and male (\u2642) symbols. Here is an example to create a plot using this symbols (I am using RStudio):
gender <- rbinom(n=100, size=100, prob=0.5)
plot(gender, cex=2.5,
pch=ifelse(gender %% 2 == 0, -0x2642L, -0x2640L),
col=ifelse(gender %% 2 == 0, 2, 3), main="\u2640 and \u2642 Symbols")
It works and generates a plot with those symbols Plot. I can save it as picture (PNG) but when I try to save it as pdf all the symbols don't show up Plot.
Here is how I try to save it as pdf:
pdf("plot.pdf")
gender <- rbinom(n=100, size=100, prob=0.5)
plot(gender, cex=2.5,
pch=ifelse(gender %% 2 == 0, -0x2642L, -0x2640L),
col=ifelse(gender %% 2 == 0, 2, 3), main="\u2640 and \u2642 Symbols")
dev.off()
I saw another post about similar problem here and it was suggested to use the CairoPDF. It did not work. I tried other family settings but it did not work either. Is there any other work around to save it as pdf with those symbols or the only way it is to save it as a picture. I would prefer to save it as pdf.
After a lot of tentatives I switched to command line and use quartz. After plotting the graph I use:
quartz.save(type = 'pdf', file = 'output.pdf')
It works perfectly. Why does it not works using the first code pdf("plot.pdf") but works with quartz.save(type = 'pdf', file = 'output.pdf')? Is it something with my system?
Thank you.
On my Mac this gives a pdf with astrological symbols. (Cobbled together from a search of similar questions on SO.) I didn't make the extra effort to "wrap" the full set neatly so the "printing of the later ones doesn't show up, but you can see Mars and Venus.
cairo_pdf("Venus_Mars.pdf",family="ArialUnicodeMS")
plot(1,1)
TestUnicode <- function(start="263c", end="2653", ...)
{
nstart <- as.hexmode(start)
nend <- as.hexmode(end)
r <- nstart:nend
s <- ceiling(sqrt(length(r)))
for(i in seq(r)) {
try(points(.6+(i/10), .8 , pch=-1*r[i],...))
}
}
TestUnicode()
dev.off()
Related
I'm trying to optimize the parameters for baseline in the R baseline package by changing each parameters in a loop and comparing plots to determine which parameters give me the best baseline.
I currently have the code written so that the loop produces each plot, but I'm having trouble with getting the plot saved as the class of each object I'm creating is a baseline package-specific (which I'm suspecting is the problem here).
foo <- data.frame(Date=seq.Date(as.Date("1957-01-01"), by = "day",
length.out = ncol(milk$spectra)),
Visits=milk$spectra[1,],
Old_baseline_visits=milk$spectra[1,], row.names = NULL)
foo.t <- t(foo$Visits)
#the lines above were copied from https://stackoverflow.com/questions/37346967/r-packagebaseline-application-to-sample-dataset to make a reproducible dataset
df <- expand.grid(lambda=seq(1,10,1), p=seq(0.01,0.1,0.01))
baselinediff <- list()
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- plot(thisplot)
jpeg(file = paste(baselinediff[[i]], '.jpeg', sep = ''))
dev.off()
}
I know that I would be able to extract corrected spectra using baseline.als but I just want to save the plot images with the red baseline so that I can see how well the baselines are getting drawn. Any baseline users out there that can help?
I suggest you change your loop in the following way:
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- thisplot
jpeg(file = paste('baseline', i, '.jpeg', sep = ''))
plot(baselinediff[[i]])
dev.off()
}
Note that this does not try to capture the already plotted element (thisplot) inside of the list. Instead, the plotting is done after you call the jpeg command. This solves your export issue. Another problem was the naming of the file. If you call baselinediff[[i]] inside of paste, you apparently end up with an error. So I switched it to a simpler name. To plot your resulting list, call:
lapply(baselinediff, plot)
If you are determined on storing the already plotted element, the capture.plotfunction from the imager package might be a good start.
This is final output I got, I'm supposed to get the final output as a single file with two bands:
Following is the code which I am using:
A11 <-brick("E:/Official/PROJECTS/R_Progrm/1.tif") // to read multiband image
B11<-brick("E:/Official/PROJECTS/R_Progrm/3.tif") // To read multiband image
mos1 <- mosaic(A11,B11,fun=max,tolerance=0.5,
filename="Mosaic_new",overwrite=TRUE)
plot(mos1,main="Mosaic_new1")
writeRaster(x=mos1,file="E:/Official/PROJECTS/R_Progrm/M11.tif",options="INTERLEAVE=BAND",format="GTiff",datatype="FLT8S",overwrite=TRUE)
The plot that you have shown in your question, is showing both the bands of your output image. So, there should not be any problem with your code and its output. If the problem is related to visualizing all the bands as an RGB Image, then you have to modify the parameters of plot function that means you have to provide the band combination. For example:
plotRGB(a, r = 4, g = 3, b = 2, axes=TRUE, main="3 Band Color Composite Image")
box(col="white")
Also, you can try the code given below which is working fine for me, and I hope it will resolve your problem.
a <- stack("Path to first raster")
b <- stack("Path to second raster")
rast.list <- list(a,b)
rast.list$fun <- mean
rast.mosaic <- do.call(mosaic,rast.list)
plot(rast.mosaic)
writeRaster(rast.mosaic,"Output_Raster_Name",format="GTiff",overwrite=TRUE)
rm(list = ls())
gc()
memory.limit(size= 2000)
library(rgdal)
library(raster)
install.packages("gdalUtils")
library(gdalUtils)
library(sp)
setwd("E:/Official/PROJECTS/R_Progrm/MOs/")
list.files()
file1=file.path(getwd(), "", "1.tif")
gdal_setInstallation()
valid_install <- !is.null(getOption("gdalUtils_gdalPath"))
if(require(raster) && require(rgdal) && valid_install)
{
layer1 <- file.path(getwd(), "", "1.tif")
layer2 <- file.path(getwd(), "", "3.tif")
file_list=c(layer1,layer2)
mosaic_rasters(gdalfile=file_list,dst_dataset="E:/Official/PROJECTS/R_Progrm/MOs//test_mosaic.GTiff",separate=TRUE,of="GTiff",verbose=TRUE)
gdalinfo("test_mosaic.GTiff")
}
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.
Problem:
Hi, I try to make an animated plot in a rmarkdown document. Here is my code:
```{r lmSim, fig.show='animate'}
library(animation)
library(plyr)
oopt = ani.options(interval = 0.3, nmax = 101)
a <- sort(rnorm(100, 2))
b <- sort(rnorm(100, 7))
out <- vector("list", 101)
for (i in 1:ani.options("nmax")) {
ji <- seq(from = 0, to = 5, by = .05)
a <- jitter(a, factor = 1, amount = ji[i])
fab1 <- lm(a ~ b)
coe <- summary(fab1)$coefficients
r2 <- summary(fab1)$r.squared
if (coe[2, 4] < .0001) p <- " < .0001"
if (coe[2, 4] < .001 & coe[2, 4] > .0001) p <- " < .001"
if (coe[2, 4] > .01) p <- round(coe[2, 4], 3)
plot(a ~ b, main = "Linear model")
abline(fab1, col = "red", lw = 2)
text(x = min(b) + 2, y = max(a) - 1,
labels = paste("t = ", round(coe[2, 3], 3), ", p = ", p, ", R2 = ", round(r2, 3)))
out[[i]] <- c(coe[2, 3], coe[2, 4], r2)
ani.pause()
}
ani.options(oopt)
```
The loop work fine, and passed into a function, I'am able to save it in several formats with 'saveLatex', 'saveHTML' or 'saveVideo'. However, when 'knit' the .Rmd file in order to obtain a PDF, the animation does not appear, there is just this line written:
video of chunk lmSim
If I knit it in HTML, only the play button of the video is displayed. However, If I open the HTML in my browser (firefox) it is displayed correctly.
There is no error message displayed. I'm using R version 3.2.0, the latest R Studio version, 1.10.5 knitr version on a MacBook Pro Yosemite. I didn't find any relevant information or documentation to solve my problem.
Questions:
So, is it simply possible to have an embeded animation into a PDF generated with rmarkdown/knitr ?
Do I have to install another program to deal with videos in PDF (I have ffmpeg on my computer)?
Many thanks!
Thanks Yihui! It works very well with the following settings (reading the PDF with Adobe):
---
title: "Sim"
author: ""
header-includes:
- \usepackage{animate}
...
---
```{r lmSim, fig.show='animate', out.width = '6in'}
Have you tried with ggplot and gganimation? For example:
library(gapminder)
library(gganimate)
library(ggplot)
head(gapminder)
theme_set(theme_bw())
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = 1, color = continent, frame = year)) +
geom_point() +
scale_x_log10()
animation<-gganimate(p, "your_animation.gif")#Or to your path
See that you need to save first your animation. You need to have establish your work directory.
After you can call it from the chat or html in markdown (not from the R chuck) like:
![your caption here](your_animation.gif)
May be it’s too late for this answer, but hopefully should help others. I recommend to save and run the R code as a separate file in the same directory and only import the animation as a gif to reduce lag in the presentation. This works for me in ioslides:
## Time series visualization
![time series](myanimation.gif){width=80%}
I have created 36 heatmaps with the function pheatmap, and I want to display them in just one figure. I have tried to using the function par(), but it did not work, I do not know why. Could someone tell me what should I do? Thank you very much. This is my code:
require(graphics);require(grDevices);library("pheatmap", lib.loc="D:/Program Files/R/R-3.1.1/library");library(gplots)
filenames<-list.files("D:/Project/bladder cancer/heatmap0829/heatmap/"); # detect all of the files in the fold
filename2<-strtrim(filenames,nchar(filenames)-4); # all of the filenames without extension names
par(mfrow=c(18,2)) #divide the graphics windows into a 18x2 matrix
for(i in 1:length(filename2)){
rt<-read.table(paste("D:/Project/bladder cancer/heatmap0829/heatmap/",filenames[i],sep = ""), header = T, sep = '\t') # Import the data with the ith file name
size=dim(rt) # the dimensional of the datafram
cw=400/size[1] #the width of the cell in the heatmap
rt<-log10(rt)
x <- t(data.matrix(rt))
pheatmap(x,color=greenred(256),main=filename2[i],cluster_rows = F, cluster_cols = T,cellwidth = cw, cellheight = 60,border_color =F,fontsize = 8,fontsize_col = 15)}
This is one dataset
ScaBER 5637
1 1.010001e+02
1.341186e+00 2.505067e+01
1.669456e+01 8.834190e+01
7.141351e+00 3.897474e+01
1.585592e+04 5.858210e+04
1 3.137979e+01
1.498863e+01 7.694948e+01
1.115443e+02 3.642917e+02
1.157677e+01 5.036716e+01
4.926492e+02 8.642784e+03
3.047117e+00 1.872154e+01
I have 36 txt files like this, but I can not put all of them here
"ScaBER 5637" is the column name of this dataset
See this previous answer: Histogram, error: Error in plot.new() : figure margins too large
par(mfcol=c(3,12), oma=c(1,1,0,0), mar=c(1,1,1,0), tcl=-0.1, mgp=c(0,0,0))
for(i in 1:36){
plot(runif(2), runif(2), type="l")
}
dev.off()