Can't store the result of pie() function R - r

I have a problem trying to store the result of my pie() function in a variable, it appears that it sets it to NULL whereas the plot is displayed, I don't understand why.
I want to store it in order to write it as an HTML file after.
Here is my code:
for(i in seq(1,13)){
values <- c(stat_pcs_region[ i,"pop_agriculteurs"], stat_pcs_region[i,"pop_commercant"], stat_pcs_region[i,"pop_cadres"],
stat_pcs_region[i,"pop_profIntermediaire"], stat_pcs_region[i,"pop_employes"], stat_pcs_region[i,"pop_ouvriers"],
stat_pcs_region[i,"pop_retraites"], stat_pcs_region[i,"pop_chomage"])
labels <- c("Agriculteurs", "Commercants, artisans et chef d entreprise", "Cadres", "Professions intermediares",
"Employes", "Ouvriers", "Retraites", "Chomeurs")
percentage <- round(values/sum(values)*100)
labels <- paste(percentage, "% de", labels)
p <- pie(values, labels, col = rainbow(9))
saveWidget(p, file = paste("C:/Users/henri/Downloads/Rapports_appli_geo/Pie_charts_regions/piechartPCS_reg", i, ".html", sep = ""))
}
Thanks in advance for your help

Related

R baseline package saving plots in a loop

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.

Error: Mapping must be created by 'aes()'

I am using a for loop to create 100 ggplots in R to be graphed onto one sheet of paper. However, I keep getting a mapping must be created by aes() error and I am not sure how to fix it.
I have tried the get function with and without environments, unclear where to go next.
for(i in 1:99){
nam <- paste("p", i, sep = "")
otunam <- paste("OTU", i, sep = "")
otunam1 <- get(otunam, envir = as.environment(histotu), inherits = TRUE)
plot <- ggplot(histotu, aes(x=otunam)) + geom_histogram(histotu, stat = "bin", binwidth = 0.01) + geom_vline(xintercept=expD[1,i], color = "red") + xlab(otunam)
assign(nam, plot)
}
I would like to clear this error and be able to make 100 graphs using grid.arrange. I have this part to work, but not the for loop to create the objects that it calls.

How can I combine several heatmaps using R in a signal figure

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()

Calculate equation from .csv file input and plot result over barplot

I coulnd't found any post with a related subject. I actually don't know if its posible.
So I have my. csv file:
Periodo;Teorico;Real;F1;F2;F3
20140101;50;20;7;7;16
20140108;55;29;11;5;5
20140115;52;21,4;8,6;10;12
20140122;66;32;9;8;17
I asign it to a data.frame:
df<-read.csv2('d:\\xxx\\test2.csv', header = T, sep = ";")
Then I do barplot function:
bp <- barplot(t(df[,-c(1:2)]),col=c("blue", "red", "green", "yellow"),legend=colnames(df[,-c(1:2)]),args.legend = list(x="topleft"))
axis(side = 1, at = bp, labels = df$Periodo)
title(main = "Teorico = Real + F1+F2+F3", font.main = 4)
Now I must calculate the following function: (efficiency function)
((Teorico-Real)/Teorico)*100
And represent the result of the function of each row on the top of each Periodo (week).
If you could help me with the code for the function and "replotting" parts or give some guidelines or posts related to this I would be really gratefull.
Thanks
You can try:
lbls <- round(((df$Teorico - df$Real) / df$Teorico)* 100)
mtext(lbls, at=bp)
(I just used round to make it look better.)

country-labels on spplot()

I'd like to add name-labels for regions on an spplot().
Example:
load(url('http://gadm.org/data/rda/FRA_adm0.RData'))
FR <- gadm
FR <- spChFIDs(FR, paste("FR", rownames(FR), sep = "_"))
load(url('http://gadm.org/data/rda/CHE_adm0.RData'))
SW <- gadm
SW <- spChFIDs(SW, paste("SW", rownames(SW), sep = "_"))
load(url('http://gadm.org/data/rda/DEU_adm0.RData'))
GE <- gadm
GE <- spChFIDs(GE, paste("GE", rownames(GE), sep = "_"))
df <- rbind(FR, SW, GE)
## working
plot(df)
text(getSpPPolygonsLabptSlots(df), labels = c("FR", "SW", "GE"))
## not working
spplot(df[1-2,])
text((getSpPPolygonsLabptSlots(df), labels = c("FR", "SW"))
The second one probably doesn't work because of lattice!?
However, I need the spplot-functionality.
How would I get the labels on the plot?
Standard way of adding some text is using the function ltext of lattice, but the coordinates given there are always absolute. In essence, you can't really rescale the figure after adding the text. Eg :
data(meuse.grid)
gridded(meuse.grid)=~x+y
meuse.grid$g = factor(sample(letters[1:5], 3103, replace=TRUE),levels=letters[1:10])
meuse.grid$f = factor(sample(letters[6:10], 3103, replace=TRUE),levels=letters[1:10])
spplot(meuse.grid, c("f","g"))
ltext(100,200,"Horror")
Produces these figures (before and after scaling)
You can use a custom panel function, using the coordinates within each panel :
myPanel <- function(x,y,xx,yy,labels,...){
panel.xyplot(x,y,...)
ltext(xx,yy,labels)
}
xyplot(1:10 ~ 1:10,data=quakes,panel=myPanel,
xx=(1:5),yy=(1:5)+0.5,labels=letters[1:5])
(run it for yourself to see how it looks)
This trick you can use within the spplot function as well, although you really have to check whatever plotting function you use. In the help files on spplot you find the possible options (polygonsplot, gridplot and pointsplot), so you have to check whether any of them is doing what you want. Continuing with the gridplot above, this becomes :
myPanel <- function(x,y,z,subscripts,xx,yy,labels,...){
panel.gridplot(x,y,z,subscripts,...)
ltext(xx,yy,labels)
}
# I just chose some coordinates
spplot(meuse.grid, c("f","g"),panel=myPanel,xx=180000,yy=331000,label="Hooray")
which gives a rescalable result, where the text is added in each panel :
Thank you, Gavin Simpson!
I finally found a way.
In the hope it helps others in the future, I post my solution:
sp.label <- function(x, label) {
list("sp.text", coordinates(x), label)
}
ISO.sp.label <- function(x) {
sp.label(x, row.names(x["ISO"]))
}
make.ISO.sp.label <- function(x) {
do.call("list", ISO.sp.label(x))
}
spplot(df['ISO'], sp.layout = make.ISO.sp.label(df))

Resources