How to store results of a simulation and plot all the results in one plot using plot_KDE in Luminescence package for R - r

I am creating a simulation using random number simulations. This gives 100 sets of 45 values with error.
First I would like to store the results of these simulations.
I then need to plot the results of these simulations on one plot. The plot I need to produce uses the package Luminescence and is of the type KDE.
I have managed to produce the separate entities but am struggling to both store the results and to produce the plot with all the simulations.
So far I have created the simulation:
Simulation <- function() {
RNC <- rescale (SFMT(45, dim=1, mexp=216091,
usepset=T, withtorus= F, usetime=T),
c(0.01,130))
RNC_error <- RNC*0.15
df <-data.frame(RNC,RNC_error)
}
the plot I want to create uses the following:
library("Luminescence")
plot_KDE(data=df, na.rm = TRUE,
values.cumulative = TRUE, order = TRUE,
boxplot = F, rug = F,
summary.method = "MCM", bw = "nrd0",
output = TRUE)
For my final result I require the numerical results of all the simulations stored and a single KDE plot with the results of all the simulations.

Split your problem into two parts.
Storing results. You have a data frame, df, so just use write.csv() to store the results to a CSV file, i.e.
write.csv(df, file="some_file.csv")
Storing your plot. Obviously you can't use a csv file, so instead we'll use a pdf or png, e.g.
# Open the file
pdf("figure_file.pdf")
plot_KDE(data=df, na.rm = TRUE,
values.cumulative = TRUE, order = TRUE,
boxplot = F, rug = F,
summary.method = "MCM", bw = "nrd0",
output = TRUE)
# Close the file
dev.off()
To save as a png use png() instead of pdf()

Related

Creating multiple plots within a loop and saving in R?

I am having trouble saving multiple plots from the output of a loop. To give some background:
I have multiple data frames, each with the data for single chemical toxicity for multiple species. I have labelled each data frame for the chemical that it represents, ie "ChemicalX". The data is in this format as this is how the "SSDTools" package works, which creates a species sensitivity distribution for a single chemical.
Because I have a lot of chemicals, I want to create a loop that iterates over each data frame, calculates the required metrics to create an SSD, plot the SSD, and then save the plot.
The code below works for calculating all of metrics and plotting the SSDs - it only breaks when I try to create a title within the loop, and when I try to save the plot within the loop
For reference, I am using the packages:
SSDTools, ggplot2, tidyverse, fitdistrplus
My code is as follows:
# Create a list of data frames
list_dfs <- list(ChemicalX, ChemicalY, ChemicalZ)
# make the loop
for (i in list_dfs){ # for each chemical (ie data frame)
ssd.fits <- ssd_fit_dists(i, dists = c("llogis", "gamma", "lnorm", "gompertz", "lgumbel", "weibull", "burrIII3", "invpareto", "llogis_llogis", "lnorm_lnorm")) # Test the goodness of fit using all distributions available
ssd.gof_fits <- ssd_gof(ssd.fits) # Save the goodness of fit statistics
chosen_dist <- ssd.gof_fits %>% # Choose the best fit distribution by
filter(aicc==min(aicc)) # finding the minimum aicc
final.fit <- ssd_fit_dists(i, dists = chosen_dist$dist) # Use the chosen distribution only
final.predict <-predict(final.fit, ci = TRUE) # generate the final predictions
plotdata <- i # create a separate plot data frame
final.plot <- ssd_plot(plotdata, final.predict, # generate the final plot
color = "Taxa",
label = "Species",
xlab = "Concentration (ug/L)", ribbon = TRUE) +
expand_limits(x = 10e6) + # to ensure the species labels fit
ggtitle(paste("Species Sensitivity for",chem_names_df[i], sep = " ")) +
scale_colour_ssd()
ggsave(filename = paste("SSD for",chem_names_df[i], ".pdf", sep = ""),
plot = final.plot)
}
The code works great right up until the last part, where I want to create a title for each chemical in each iteration, and where I want to save the filename as the chemical name.
I have two issues:
I want the title of the plot to be "Species Sensitivity for ChemicalX", with ChemicalX being the name of the data frame. However, when I use the following code the title gets all messed up, and gives me a list of the species in that data frame (see image).
ggtitle(paste("Species Sensitivity. for",i, sep = " "))
Graph title output using "i"
To try and get around this, I created a vector of chemical names that matches the order of the data frame list, called "chem_names_df". When I use ggtitle(paste("Species Sensitivity for",chem_names_df[i], sep = " ")) however, it gives me the error of Error in chem_names_df[i] : invalid subscript type 'list'
A similar issue is happening when I try to save the plot using GGSave. I am trying to save the filenames for each chemical data frame as "SSD_ChemicalX", except similarly to above it just outputs a list of the species in the place of i.
I think it has something to do with how R is calling from my list of dataframes - I am not sure why it is calling the species list (ie c("Danio Rerio, Lepomis macrochirus,...)) instead of the chemical name.
Any help would be appreciated! Thank you!
Basically your problem here is that you are sometimes using i as if it is an index, and sometimes as if it is a data frame, but in fact it is a data frame.
Your example is not reproducible so let me provide one. You have done the equivalent of:
list_dfs2 <- list(mtcars, mtcars, cars)
for(i in list_dfs2){
print(i)
}
This is just going to print the whole mtcars dataset twice and then the cars dataset. You can then define a vector:
cars_names <- c("mtcars", "mtcars", "cars")
If you call cars_names[i], on the first iteration you're not calling cars_names[1], you're trying to subset a vector with an entire data frame. That won't work. Better to seq_along() your list of data frames and then subset it with list_dfs[[i]] when you want to refer to the actual data frame rather than the index, i. Something like:
# Create a list of data frames
list_dfs <- list(ChemicalX, ChemicalY, ChemicalZ)
# make the loop
for (i in seq_along(list_dfs)){ # for each chemical (ie data frame)
ssd.fits <- ssd_fit_dists(list_dfs[[i]], dists = c("llogis", "gamma", "lnorm", "gompertz", "lgumbel", "weibull", "burrIII3", "invpareto", "llogis_llogis", "lnorm_lnorm")) # Test the goodness of fit using all distributions available
ssd.gof_fits <- ssd_gof(ssd.fits) # Save the goodness of fit statistics
chosen_dist <- ssd.gof_fits %>% # Choose the best fit distribution by
filter(aicc==min(aicc)) # finding the minimum aicc
final.fit <- ssd_fit_dists(list_dfs[[i]], dists = chosen_dist$dist) # Use the chosen distribution only
final.predict <-predict(final.fit, ci = TRUE) # generate the final predictions
plotdata <- list_dfs[[i]] # create a separate plot data frame
final.plot <- ssd_plot(plotdata, final.predict, # generate the final plot
color = "Taxa",
label = "Species",
xlab = "Concentration (ug/L)", ribbon = TRUE) +
expand_limits(x = 10e6) + # to ensure the species labels fit
ggtitle(paste("Species Sensitivity for",chem_names_df[i], sep = " ")) +
scale_colour_ssd()
ggsave(filename = paste("SSD for",chem_names_df[i], ".pdf", sep = ""),
plot = final.plot)
}
Consider using a defined method that receives name and data frame as input parameters. Then, pass a named list into the method using Map to iterate through data frames and corresponding names elementwise:
Function
build_plot <- function(plotdata, plotname) {
# Test the goodness of fit using all distributions available
ssd.fits <- ssd_fit_dists(
plotdata,
dists = c(
"llogis", "gamma", "lnorm", "gompertz", "lgumbel", "weibull",
"burrIII3", "invpareto", "llogis_llogis", "lnorm_lnorm"
)
)
# Save the goodness of fit statistics
ssd.gof_fits <- ssd_gof(ssd.fits)
# Choose the best fit distribution by finding the minimum aicc
chosen_dist <- filter(ssd.gof_fits, aicc==min(aicc))
# Use the chosen distribution only
final.fit <- ssd_fit_dists(plotdata, dists = chosen_dist$dist)
# generate the final predictions
final.predict <- predict(final.fit, ci = TRUE)
# generate the final plot
final.plot <- ssd_plot(
plotdata, final.predict, color = "Taxa", label = "Species",
xlab = "Concentration (ug/L)", ribbon = TRUE) +
expand_limits(x = 10e6) + # to ensure the species labels fit
ggtitle(paste("Species Sensitivity for", plotname)) +
scale_colour_ssd()
# export plot to pdf
ggsave(filename = paste0("SSD for ", plotname, ".pdf"), plot = final.plot)
# return plot to environment
return(final.plot)
}
Call
# create a named list of data frames
chem_dfs <- list(
"ChemicalX"=ChemicalX, "ChemicalY"=ChemicalY, "ChemicalZ"=ChemicalZ
)
chem_plots <- Map(build_plot, chem_dfs, names(chem_dfs))

Saving output plot in R with grid.grab() doesn't work

I've been trying to save multiple plot generated with the meta package in R, used to conduct meta-analysis, but I have some troubles. I need to save this plot to arrange them in a multiple plot figure.
Example data:
s <- data.frame(Study = paste0("Study", 1:15),
event.e = sample(1:100, 15),
n.e = sample(100:300, 15))
meta1 <- meta::metaprop(event = event.e,
n= n.e,
data=s,
studlab = Study)
Here is the code:
meta::funnel(meta1)
funnelplot <- grid::grid.grab()
I can see the figure in the "plot" tab in R Studio; However, if I search the funnelplot object in the environment it say that is a "NULL" type, and obviously trying to recall that doesn't work.
How can I fix it?

get results of principal Component Analysis in R

I want to get the results of PC1 and PC2 to plot courbe of both in the same graph with tableau desktop.
How to do?
data = read.csv(file="data.csv",header=TRUE, sep=";")
data.active <- data[, 1:30]
library(factoextra)
res.pca <- prcomp(data.active,center = TRUE, scale. = TRUE)
fviz_eig(res.pca)
I think you need to write a csv with the results in between R and Tableau. The code for that is written bellow :
# Principal Components Analysis
res.pca <- stats::prcomp(iris[,-5],center = TRUE, scale. = TRUE)
# Choose number of dimension kept
factoextra::fviz_eig(res.pca)
# Some visualisation
factoextra::fviz_pca_var(res.pca)
factoextra::fviz_pca_ind(res.pca)
factoextra::fviz_pca_biplot(res.pca)
# access transformed points
str(res.pca)
res.pca$x
# save points in csv to use outside of R
utils::write.csv(x = res.pca$x, file = "path/data_pca.csv")
# Load your data and do graphs the usual way with tableau
I used ?prcomp to find the data in the result, you may also push further your analysis and use some nice graphics (biplots of individual / variable, clustering, ...) with R (and import only images in Tableau) using : link

Save automatically produced plots in R

I'm using a function in R able to analyse my data and produce several plots.
The function is "snpzip" from adegenet package.
I would like to save automatically the three plots that the function produces as part of the output. Do you have any suggestion on how to do it?
I want to point to the fact that I know how to save a single plot, for instance with png or pdf followed by dev.off(). My problem is that when I run snpzip(snps, phen, method = "centroid"), the outcomes are three plots (which I would like to save).
I report here the same example as in the "adegenet" package:
simpop <- glSim(100, 10000, n.snp.struc = 10, grp.size = c(0.3,0.7),
LD = FALSE, alpha = 0.4, k = 4)
snps <- as.matrix(simpop)
phen <- simpop#pop
outcome <- snpzip(snps, phen, method = "centroid")
If you use a filename with a C integer format in it, then R will substitute the page number for that part of the name, generating multiple files. For example,
png("page%d.png")
plot(1)
plot(2)
plot(3)
dev.off()
will generate 3 files, page1.png, page2.png, and page3.png. For pdf(), you also need onefile=FALSE:
pdf("page%d.pdf", onefile = FALSE)
plot(1)
plot(2)
plot(3)
dev.off()

Extracting values from a graph

I have a graph that is created by complex numbers from the function below. I would like to extract the resulting data points which correpond with the line from the data plot as to be able to work with a vector of data.
library(multitaper)
NW<-10
K<-5
x<-c(2,3,1,3,4,6,7,8,5,4,3,2,4,5,7,8,6,4,3,2,4,5,7,8,6,4,5,3,2,5,7,8,6,4,5,3,6,7,8,8,9,7,6,5,4,7)
resSpec <- spec.mtm(as.ts(x), k= K, nw=NW, nFFT = length(x),
centreWithSlepians = TRUE, Ftest = TRUE,
jackknife = FALSE, maxAdaptiveIterations = 100,
plot =FALSE, na.action = na.fail)
plot(resSpec)
What would be the best procedure. I have tried saving the plot in emf. I wanted to use package ReadImages which was I believe the right package. (however this was not available for R versiĆ³n 3.02 so I could not use it). What would be the correct procedure of saving and extracting and are there other packages and in what file types could I save the graph (as far as I can see R (OS windows) only permist emf.)
Any help welcomed

Resources