Save plots generated by repeat function - r

Currently I am looking for a solution to save 72 plots to an PDF file.
Those 72 plots are created through a function and the below code of repeat.
The ID stands for a person within my dataset. This person has multiple rows of data attached to his ID. To go to the next person I use ID = ID + 1
With the below code I manage to create an PDF file but, this is a PDF file with 72 pages. I would like to have 4 plots on each row. Something in the idea of nrow = 4 like you use in grid.arrange. Preferably 4 on each row and 24 on each page.
pdf("plot1.pdf")
repeat {
ID = ID + 1
print(ggplot(ID))
if (ID == 72){
break}}
dev.off()

I am still not sure wether this is a legit solution but at least it is fixed now!
Apparently I was looking for a solution like this:
plot.list <- list()
for(i in 1:72){
plot.list[[length(plot.list) + 1]] <- plot_utility(i)
}
grid1 <- grid.arrange(grobs = plot.list, ncol = 4)
ggsave("plot1.pdf",
plot = grid1,
device = "pdf",
scale = 2,
width = 25,
height = 20,
units = c("cm")
)

Related

I can't get my plots to a single grid please help correct my code

I have 11 plots and used a looping function to plot them see my code below. However, I can't get them to fit in just 1 page or less. The plots are actually too big. I am using R software and writing my work in RMarkdown. I have spent almost an entire week trying to resolve this.
group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i <- graph3$plots[[i]] +
labs(title = Firm_category[i]) +
stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
#output3.long data sample below as comments
#Firm_category billmonth Means.type means
#Agric 1 Before 38.4444
#Agric 1 After 51.9
Complete data is on my github: https://github.com/Fridahnyakundi/Descriptives-in-R/blob/master/Output3.csv
This code prints all the graphs but in like 4 pages. I want to group them into a grid. I have tried to add all these codes below just before my last curly bracket and none is working, please help me out.
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))
library(ggpubr)
print(ggarrange(graph3.i[1:11], nrow = 4, ncol = 3))
I tried the gridExtra command as well (they all seem to do the same thing). I am the one with a mistake and I guess it has to do with my list. I read a lot of similar work here, some suggested
dev.new()
dev.off()
I still didn't get what they do. But adding either of them caused my code to stop.
I tried defining my 'for' loop function say call it 'XX', then later call it to make a list of graph but it returned NULL output.
I have tried defining an empty list (as I read in some answers here) then counting them to make a list that can be printed but I got so many errors.
I have done this for almost 3 days and will appreciate your help in resolving this.
Thanks!
I tried to complete your code ... and this works (but I don't have your 'stat.test' object). Basically, I added a graph3.i <- list() and replaced graph3.i in the loop ..
Is it what you wanted to do ?
library(magrittr)
library(dplyr)
library(rstatix)
library(ggplot2)
library(ggpubr)
data <- read.csv(url('http://raw.githubusercontent.com/Fridahnyakundi/Descriptives-in-R/master/Output3.csv'))
graph3 <- data %>% group_by(Firm_category) %>%
doo(
~ggboxplot(
data =., x = "Means.type", y = "means",
fill ="grey", palette = "npg", legend = "none",
ggtheme = theme_pubr()
),
result = "plots"
)
graph3
# Add statistical tests to each corresponding plot
graph3.i <- list()
Firm_category <- graph3$Firm_category
xx <- for(i in 1:length(Firm_category)){
graph3.i[[i]] <- graph3$plots[[i]] +
labs(title = Firm_category[i]) # +
# stat_pvalue_manual(stat.test[i, ], label = "p.adj.signif")
print(graph3.i)
}
library(cowplot)
print(plot_grid(plotlist = graph3.i[1:11], nrow = 4, ncol = 3))

Listing All Variables (Column Names) in R Shiny's checkboxGroupInput

I'm writing an R shiny application. I'm facing much trouble, particularly the checkboxGroupInput function. I'm hoping that I will be able to create a dynamic list that will automatically list down all columns except the first column, source_file$Date of a dataset named source_file, and I'm not entirely sure on it. Would greatly appreciate any help you can provide!
Sample dataset of source_file would look something like this:
Date
Index 1
Index 2
Index 3
Index 4
Index 5
2016-01-01
+5%
-2%
+5%
+10%
+12%
2016-01-08
+3%
+13%
-8%
-3%
+10%
2016-01-15
+2%
+11%
-3%
+4%
-15%
The end goal is that I hope the checkboxGroupInput function will be able to automatically read all columns starting from the second column (ignore Date). In this case, the check box would load up 5 options, Index 1 to Index 5. It should be replicable such that it can load any number of indexes depending on the data specified. I tried hard-coding each individual index in but it's definitely counter-intuitive and so frustrating to do.
tabPanel("Target Volatility Portfolio",
sidebarPanel(
tags$h3("Find an optimised portfolio to achieve maximum return for a given level of risk/volatility"),
tags$h4("Input:"),
checkboxGroupInput("portfolio_selection",
"Select Number of Indexes for Portfolio",
choices = list(#####please send help here#####)
Edits: Would appreciate if you could help me fix this.
I want to reference the output that comes from the checkbox into my global.R in this format. Basically, I want to use the selected variables to plot a graph. A selection of 2 variables will result in a graph plotting a graph related to the 2 variables, whereas a selection of 10 variables will create a plot involving all 10 variables. (I'm basically plotting the efficient market frontier of x number of stocks where x is the number of variables selected. Its a little hard to explain but I hope attaching the code can provide you some insight) The hashed line is what I need help fixing. Thank you!
plot_emf = function(n_points, target_vol, portfolio_selection)
{
first <- portfolio_selection[1]
last <- portfolio_selection[length(portfolio_selection)]
#######asset_returns = source_file[first:last]########
# Extract necessary parameters
n_assets = ncol(asset_returns)
n_obs = nrow(asset_returns)
n_years = n_obs / 52
# Initialize containers for holding return and vol simulations
return_vector = c()
vol_vector = c()
sharpe_vector = c()
for (i in 1:n_points)
{
# Generate random weights for n assets from uniform(0,1)
asset_weights = runif(n_assets, min = 0, max = 1)
normalization_ratio = sum(asset_weights)
# Asset weights need to add up to 100%
asset_weights = asset_weights / normalization_ratio
# print(asset_weights)
# print(asset_returns)
# Generate the portfolio return vector using these weights
random_portfolio_returns = emf_portfolio_returns(
asset_weights,
asset_returns)
# print(random_portfolio_returns)
# plot_returns_histogram(random_portfolio_returns$portfolio_returns)
cumulative_return = calculate_cumulative_return(random_portfolio_returns$portfolio_returns)
annualized_return = 100*((1 + cumulative_return/100)^(1/n_years) - 1)
annualized_vol = sd(random_portfolio_returns$portfolio_returns)*(52^0.5)
sharpe = annualized_return / annualized_vol
return_vector = append(return_vector, annualized_return)
vol_vector = append(vol_vector, annualized_vol)
sharpe_vector = append(sharpe_vector, sharpe)
#print(paste("Asset weights:",asset_weights))
#print(paste("Anualized return:",annualized_return))
#print(paste("Annualized vol:",annualized_vol))
}
g = ggplot(data = data.frame(vol_vector, return_vector, sharpe_vector),
aes(x = vol_vector, y = return_vector, color = sharpe_vector)) +
scale_color_gradient(low = "red", high = "blue", name = "Sharpe Ratio\n(Return/Risk)") +
ggtitle("Efficient Market Frontier") +
xlab("Annualized Vol (%)") +
ylab("Annualized Return (%)") +
theme(plot.title = element_text(hjust=0.5)) + geom_vline(xintercept=target_vol) +
geom_point()
print(g)
}
You can try something like the following which uses colnames() to extract the new choices, and then updates the checkboxGroupInput with updateCheckboxGroupInput():
server <- function(input, output, session) {
# Read the data once per session - this step might be better to
# put in a `global.R` file
source_file <- read.csv("source_file.csv")
# Column names we want to show - all except `Date`
opts <- setdiff(colnames(source_file), "Date")
# Update your checkboxGroupInput:
updateCheckboxGroupInput(
session, "portfolio_selection", choices = opts
)
# Rest of app after this point --------------------------------------
}

Create and combine 2 grid.tables

I have created a grid.table object to display a dataframe in PowerBi, below there is my code:
dataset <- data.frame(BDS_ID = c("001","002"),
PRIORITY = c("high","medium"),
STATUS = c("onair","onair"),
COMPANY = c("airfr","fly"))
my.result <- melt(dataset, id = c("BDS_ID"))
mytheme <- ttheme_default(base_size = 10,
core=list(fg_params=list(hjust=0, x=0.01),
bg_params=list(fill=c("white", "grey90"))))
for (i in 1:nrow(tg)) {
tg$grobs[[i]] <- editGrob(tg$grobs[[i]], gp=gpar(fontface="bold"))
}
grid.draw(tg)
and this is my output:
I would like to improve my output in the following way: I would like that the row headers to be unique and have a different column for each different value of each variable repeating the column with the row headers each time.
I tried to do this using the statement t(dataset), but I do not get the desired result because the row headers are not repeated.
I would like to get an output (always classy grob) similar to this:
**PRIORITY** high **PRIORITY** medium
**STATUS** onair **STATUS** onair
**COMPANY** airfr **COMPANY** fly
Does anyone knows how to achive this?
Thanks
I'm unable to reproduce the grob format you've shown based on the code you've provided, but I've got something similar:
dataset <- data.frame(BDS_ID = c("001","002"),
PRIORITY = c("high","medium"),
STATUS = c("onair","onair"),
COMPANY = c("airfr","fly"))
dataset <- data.frame(t(dataset))
dataset$label1 <- rownames(dataset)
dataset$label2 <- rownames(dataset)
colnames(dataset) <- c("status1", "status2", "label1", "label2")
dataset <- dataset[c(2:nrow(dataset)), c(3, 1, 4, 2)]
rownames(dataset) <- NULL
test <- grid.draw(tableGrob(dataset))
The above code produces the following object. It doesn't look exactly like yours, but it's in the general structure you're looking for:

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

Saving a plot from R and then copying it to a Word text file [duplicate]

This question already has answers here:
How to save a plot as image on the disk?
(11 answers)
Closed 8 years ago.
What I have tried so far:
par( mfrow = c( 1, 2 ) )
matplot(rOU,type="l", ylim=range(rOU))
matplot(rEM,type="l", ylim=range(rEM))
here is sample code taken from The R Statistics Website
Basically you have to
Create a new Word file
Create headers and sub-headers
Move to a new pages in the document
Write text
Insert tables (that is “data.frame” and “matrix”objects)
Insert plots
Save and close the Word document
Code:
# install.packages("R2wd")
# library(help=R2wd)
require(R2wd)
wdGet(T) # If no word file is open, it will start a new one - can set if to have the file visiable or not
wdNewDoc("c:\\This.doc") # this creates a new file with "this.doc" name
wdApplyTemplate("c:\\This.dot") # this applies a template
wdTitle("Examples of R2wd (a package to write Word documents from R)") # adds a title to the file
wdSection("Example 1 - adding text", newpage = T) # This can also create a header
wdHeading(level = 2, "Header 2")
wdBody("This is the first example we will show")
wdBody("(Notice how, by using two different lines in wdBody, we got two different paragraphs)")
wdBody("(Notice how I can use this: '\ n' (without the space), to \n go to the next
line)")
wdBody("האם זה עובד בעברית ?")
wdBody("It doesn't work with Hebrew...")
wdBody("O.k, let's move to the next page (and the next example)")
wdSection("Example 2 - adding tables", newpage = T)
wdBody("Table using 'format'")
wdTable(format(head(mtcars)))
wdBody("Table without using 'format'")
wdTable(head(mtcars))
wdSection("Example 3 - adding lm summary", newpage = T)
## Example from ?lm
ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2,10,20, labels=c("Ctl","Trt"))
weight <- c(ctl, trt)
# This wouldn't work!
# temp <- summary(lm(weight ~ group))
# wdBody(temp)
# Here is a solution for how to implent the summary.lm output to word
wdBody.anything <- function(output)
{
# This function takes the output of an object and prints it line by line into the word document
# Notice that in many cases you will need to change the text font into courier new roman...
a <- capture.output(output)
for(i in seq_along(a))
{
wdBody(format(a[i]))
}
}
temp <- summary(lm(weight ~ group))
wdBody.anything(temp)
wdSection("Example 4 - Inserting some plots", newpage = T)
wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 20)
wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 20)
wdPlot(rnorm(100), plotfun = plot, height = 10, width =20, pointsize = 50)
# wdPageBreak()
wdSave("c:\\This.doc") # save current file (can say what file name to use)
wdQuit() # close the word file

Resources