I am trying to create an incremental HE plot in an R notebook that will be compiled to HTML (so a .R file). The function I am using heplot() from the heplots package uses an add = TRUE parameter to overlay the graphic over the previous one, which is useful when there are multiple groups you wish to compare.
If I run this as an R notebook, I get the following error:
Error in polygon(E.ellipse, col = last(fill.col), border = last(col), :
plot.new has not been called yet
Calls: <Anonymous> ... withVisible -> eval -> eval -> heplot -> heplot.mlm -> polygon
I believe this is because the R notebook is not keeping the previous plot in memory when it evaluates the second plot.
Here is a reproducible example of the problematic R notebook file (save as .R):
#' ---
#' title: "Incremental HE Plots Test"
#' author: "Matthew Sigal"
#' date: "08 Jun 2016"
#' ---
#' ## Load package and data:
library(heplots)
data(Rohwer, package="heplots")
#' ## Multivariate models for two subsets:
rohwer.ses1 <- lm(cbind(SAT, PPVT, Raven) ~ n + s + ns + na + ss,
data = Rohwer, subset = SES == "Hi")
rohwer.ses2 <- lm(cbind(SAT, PPVT, Raven) ~ n + s + ns + na + ss,
data = Rohwer, subset = SES == "Lo")
#' ## Overlaid visualization:
heplot(rohwer.ses2, col = c("red", rep("black",5), "blue"),
hypotheses = list("B=0, Low SES" = c("n", "s", "ns", "na", "ss")),
level = 0.5, cex = 1.25,
fill = c(TRUE, FALSE), fill.alpha = 0.05,
xlim = c(-15, 110), ylim = c(40, 110),
label.pos = c(1, rep(NULL, 5), 1))
#' ## High SES students:
heplot(rohwer.ses1, col = c("red", rep("black", 5), "blue"),
hypotheses = list("B=0, High SES" = c("n", "s", "ns", "na", "ss")),
level = 0.5, cex = 1.25,
add = TRUE, # place both plots on same graphic
error = TRUE, # error ellipse is not drawn by default with add = TRUE
fill = c(TRUE, FALSE), fill.alpha = 0.05,
xlim = c(-15, 110), ylim = c(40, 110))
I thought that maybe using a chunk option, such as fig.show="hold" might work, but this did not solve the issue.
If I knit this in an Rmarkdown document, it works as expected (save as .Rmd):
---
title: "Rmd Test"
author: "Matthew Sigal"
date: "June 9, 2016"
output: html_document
---
## Test
```{r}
library(heplots)
data(Rohwer, package="heplots")
rohwer.ses1 <- lm(cbind(SAT, PPVT, Raven) ~ n + s + ns + na + ss,
data = Rohwer, subset = SES == "Hi")
rohwer.ses2 <- lm(cbind(SAT, PPVT, Raven) ~ n + s + ns + na + ss,
data = Rohwer, subset = SES == "Lo")
heplot(rohwer.ses2, col = c("red", rep("black",5), "blue"),
hypotheses = list("B=0, Low SES" = c("n", "s", "ns", "na", "ss")),
level = 0.5, cex = 1.25,
fill = c(TRUE, FALSE), fill.alpha = 0.05,
xlim = c(-15, 110), ylim = c(40, 110),
label.pos = c(1, rep(NULL, 5), 1))
heplot(rohwer.ses1, col = c("red", rep("black", 5), "blue"),
hypotheses = list("B=0, High SES" = c("n", "s", "ns", "na", "ss")),
level = 0.5, cex = 1.25,
add = TRUE, # place both plots on same graphic
error = TRUE, # error ellipse is not drawn by default with add = TRUE
fill = c(TRUE, FALSE), fill.alpha = 0.05,
xlim = c(-15, 110), ylim = c(40, 110))
```
So, my question is: how can I get the Rnotebook compiler to act similarly to the Rmarkdown compiler?
Apparently, my issue was very minor - my comment for the second HE plot created a new chunk, which is what caused the error.
A working script simply removes the #' from the comment between the two calls to heplot()!
Related
I am trying to create a forestplot, using forestplotter function, am able to get a beautiful graph, but am not able to see the entire graph, the column widths in few of the columns are so big, even if the string size is less, making the width of the entire graph, so big to see, can someone help me with this and also is it possible to align the datahrame contents uniformly centre aligned......Please help me with this
The code and relevant data are
###Required packages###
library(grid)
library(forestploter)
library(rmeta)
library(gridExtra)
#Data entered#
df <- data.frame(Study=c("A","B","C","D","Summary"),
nA = c(24,187,36,26,273),
median_A = c(4.9,5.69,8.866995074,8.5,NA),
Q1A =c(3,2.86,4.495073892,2,NA),
Q3A =c(8.5,9.78,14.96305419,32,NA),
nP = c(23,193,36,26,278),
median_P = c(7.2,6.79,8.990147783,12.5,NA),
Q1P =c(3.4,3.59,4.002463054,2,NA),
Q3P =c(10.9,10.12,12.06896552,43,NA),
W = c("10.6%","80.8%","8.0%","0.70%",NA),
E=c(-2.3,-1.1,-0.123152709,-4,-1.16881587),
UL=c(1.161473203,0.156288294,3.881699516,10.02689306,-0.039791047),
LL=c(-5.761473203,-2.356288294,-4.128004935,-18.02689306,-2.297840692))
#Calculate SE for box size#
df$SE <- (df$UL-df$E)/1.96
#Column for Confidence intervals for Drug A and Placebo, with 2 significant digit#
df$IQRA <- sprintf("%.2f (%.2f to %.2f)",df$median_A,df$Q1A, df$Q3A)
df$IQRP <- sprintf("%.2f (%.2f to %.2f)",df$median_P,df$Q1P, df$Q3P)
#Column for Confidence intervals for NET EFFECT, with 2 significant digit#
df$MD <- sprintf("%.2f (%.2f to %.2f)", df$E, df$LL, df$UL)
#Create a column with space for forest plot#
df$" "<- paste(rep(" ", 16), collapse = " ")
##Forest plot theme##
#To be modified as needed#
ftn <-forest_theme(
base_size = 16,
base_family = "serif",
ci_pch = 15,
ci_col = "black",
ci_lty = 1,
ci_lwd = 1,
ci_Theight = 0.25,
legend_name = " ",
legend_position = "right",legend_value = "",
xaxis_lwd = 1,
xaxis_cex = 0.7,
refline_lwd = 1,
refline_lty = "dashed",
refline_col = "red",
summary_fill = "blue",
summary_col = "blue",
footnote_cex = 0.4,
footnote_fontface = "plain",
footnote_col = "black",
title_just = c("center"),
title_cex = 1.1,
title_fontface = "bold",
title_col = "black",
show.rownames = FALSE)
##Table in Order for Forest plot##
#First get Column names#
colnames(df)
df2 <-df[,c(1,2,15,6,16,18,17)]
#Make NA cells empty
df2[5,3] <-c(" ")
df2[5,5] <-c(" ")
##Forestplot##
plot<-forest(df2,
est = df$E,
lower = df$LL,
upper = df$UL,
sizes = (df$SE/10),
ci_column = 6,
ref_line = 0,
arrow_lab = c("Drug A Better", "Placebo Better"),
xlim = c(-7, 6),
is_summary = c(FALSE,FALSE,FALSE,FALSE,TRUE),
xlog = FALSE,
ticks_digits = 0,ticks_at = c(-6,0,6),
theme = ftn)
##Show plot
print(plot, autofit = FALSE)
I am trying to create an heatmap with a row annotation inclusive of p-values as reported in the example in the guide for the use of the ComplexHeatmap package (https://jokergoo.github.io/ComplexHeatmap-reference/book/heatmap-annotations.html#simple-annotation).
I tried to reproduce the example:
library(ComplexHeatmap)
library(circlize) # colorRamp2 function
set.seed(123)
pvalue = 10^-runif(10, min = 0, max = 3)
is_sig = pvalue < 0.01
pch = rep("*", 10)
pch[!is_sig] = NA
# color mapping for -log10(pvalue)
pvalue_col_fun = colorRamp2(c(0, 2, 3), c("green", "white", "red"))
ha = HeatmapAnnotation(
pvalue = anno_simple(-log10(pvalue), col = pvalue_col_fun, pch = pch),
annotation_name_side = "left")
ht = Heatmap(matrix(rnorm(100), 10), name = "mat", top_annotation = ha)
# now we generate two legends, one for the p-value
# see how we define the legend for pvalue
lgd_pvalue = Legend(title = "p-value", col = pvalue_col_fun, at = c(0, 1, 2, 3),
labels = c("1", "0.1", "0.01", "0.001"))
# and one for the significant p-values
lgd_sig = Legend(pch = "*", type = "points", labels = "< 0.01")
# these two self-defined legends are added to the plot by `annotation_legend_list`
draw(ht, annotation_legend_list = list(lgd_pvalue, lgd_sig))
but when I am creating the annotation ha I get the error
Error in anno_simple(-log10(pvalue), col = pvalue_col_fun, pch = pch) :
could not find function "anno_simple"
likely showing a possible problem with the package.
The version of the ComplexHeatmap package I am running is 1.20.0.
The R version is 3.5.1.
Could you please help me solving this problem?
Thanks
I have SSIS package that gets data into database and then executes R Script. R script creates new folder (names it based on the current date) and generate some pdf files into this folder. I have deployed this package on server and created Job that executes it every night. The problem is that each morning I am finding only empty folders (with correct date name) without any pdf files. However, If I execute that package manually in Visual Studio it works fine and pdfs are there. Am I missing something here? I appreciate every answer.
EDIT
When I execute manually it is directly on the server
Package looks like this
and here is my R script
dir.create(file.path(output.path, date))
library(RODBC)
conn <- odbcConnect("Azure", uid = "aaaaa", pwd = "aaaaa")
etldata <- sqlFetch(conn,"dbo.EtlLogsData", stringsAsFactors = FALSE)
pdf(paste('ETL_Duration_For_Effective_Date_', date,'.pdf',sep = ""),
width = 12,
height = 8,
paper = 'special')
par(mar = c(5, 17, 5, 3))
plot(c(min(etldata_day$st_sec), max(etldata_day$et_sec)),
c(sn[1], sn[1]),
ylim = c(0, n),
yaxt = 'n',
xaxt = 'n',
ylab = '',
xlab = 'Time',
main = paste('ETL Duration With Effective Date ', date, sep = ""))
abline(h = sn, untf = FALSE, col = "gray90")
for (i in 1:n){
lines(c(etldata_day$st_sec[i], etldata_day$et_sec[i]),
c(sn[i], sn[i]),
type = "l", lwd = 2)
arrows(etldata_day$st_sec[i], sn[i],
etldata_day$et_sec[i], sn[i],
length = 0.025, angle = 90, lwd = 2)
arrows(etldata_day$et_sec[i], sn[i],
etldata_day$st_sec[i], sn[i],
length = 0.025, angle = 90, lwd = 2)
}
# Print y axis labels
axis(2, at = sn, labels = etldata_day$TaskName, las = 1, cex.axis = 1)
# Print x axis labels
xat <- seq(from = min(etldata_day$st_sec), to = max(etldata_day$et_sec), length.out = 10)
xlabels <- secondsToString(xat)
axis(1, at = xat, labels = substr(xlabels,1,8), cex.axis = 1)
dev.off()
After plot() I use some FOR cycles, and LINES(),
I'm using boxplot() in R. My code is:
#rm(list=ls())
#B2
fps_error <- c(0.058404273, 0.028957446, 0.026276044, 0.07084294, 0.078438563, 0.024000178, 0.120678965, 0.081774358, 0.025644741, 0.02931614)
fps_error = fps_error *100
fps_qp_error <-c(1.833333333, 1.69047619, 1.666666667, 3.095238095, 2.738095238, 1.714285714, 3.634146341, 5.142857143, 1.238095238, 2.30952381)
bit_error <- c(0.141691737, 0.136173785, 0.073808209, 0.025057931, 0.165722097, 0.004276999, 0.365353752, 0.164757488, 0.003362543, 0.022423845)
bit_error = bit_error *100
bit_qp_error <-c(0.666666667, 0.785714286, 0.428571429, 0.142857143, 0.785714286, 0.023809524, 1.523809524, 0.976190476, 0.023809524, 0.142857143)
ssim_error <-c(0.01193773, 0.015151569, 0.003144532, 0.003182908, 0.008125274, 0.013796366, 0.00359078, 0.019002591, 0.005031524, 0.004370175)
ssim_error = ssim_error * 100
ssim_qp_error <-c(3.833333333, 1.80952381, 0.69047619, 0.571428571, 2, 1.904761905, 0.761904762, 2.119047619, 0.857142857, 0.976190476)
all_errors = cbind(fps_error, bit_error, ssim_error)
all_qp_errors = cbind(fps_qp_error, bit_qp_error, ssim_qp_error)
modes = cbind(rep("FPS error",10), rep("Bitrate error",10), rep("SSIM error",10))
journal_linear_data <-data.frame(fps_error, fps_qp_error,bit_error,bit_qp_error,ssim_error,ssim_qp_error )
yvars <- c("fps_error","bit_error","ssim_error")
yvars_qp <-c("fps_qp_error","bit_qp_error","ssim_qp_error")
xvars <- c("FPS", "Bitrate", "SSIM")
graphics.off()
bmp(filename="boxplot_B2_error.bmp")
op <- par(mfrow = c(1, 3), #matrix of plots
oma = c(0,0,2,0),mar=c(5.1, 7.1, 2.1, 2.1),mgp=c(4,1,0)) #outer margins
par(cex.lab=3)
par(cex.axis=3)
for (i in 1:3) {boxplot(journal_linear_data[,yvars[i]], xlab=xvars[i], ylab="Percentage error", outcex = 2)}
par(op)
mtext(text="Percentage error per mode for B2",side=3, line=1.5, font=2, cex=2,adj=0.95, col='black')
dev.off()
The image output is shown below. As you can see the y-axis does not have the same range for all graphs. How can I fix this? For example starting in 0.5 or 0.
You can simply put an ylim = c(0, 5) in all your boxplot() call. This sets y-axis range (roughly) between 0 and 5.
Perhaps you did not see ylim argument in ?boxplot; the "Arguments" section also does not mention it. But ylim is just a trivial graphical parameter passed via "...". You can also find such example in the "Examples" session of ?boxplot:
boxplot(len ~ dose, data = ToothGrowth,
boxwex = 0.25, at = 1:3 - 0.2,
subset = supp == "VC", col = "yellow",
main = "Guinea Pigs' Tooth Growth",
xlab = "Vitamin C dose mg",
ylab = "tooth length",
xlim = c(0.5, 3.5), ylim = c(0, 35), yaxs = "i")
My goal is to assign a plot produced by the pyramid package to a list. Later, I will have that plot and others inserted from the list into a document. But the pyramid function appears not to return a value. How can I assign the pyramid plot to an object?
install.packages("pyramid") # functions to draw a population pyramid
library(pyramid)
# create a mock data frame to comparing this plot to a counterpart from plotrix
df <- data.frame(level1 = c(9,9,4,3,34,28), levelsame = c(9,9,4,3,34,28),
title = c("Dir", "Exec. Dir", "Mgr", "Sr. Mgr", "Mgt Princ", "EVP+"))
# assign the plot (hopefully) to an object
empty <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> empty
NULL
Likewise, if I assign the pyramid call to my list, nothing happens. There is no value for the list returned by pyramid.
plotlist2[["pyramid"]] <- pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
> plotlist2[1]
[[1]]
NULL
I fear I am blundering in some obvious mis-understanding, so I welcome being set aright. Thank you.
You can use the recordPlot() function to save the current plot to a variable.
In your case you could do:
#print the plot
pyramid(df, Laxis = seq(1,35,5), AxisFM = "g", Csize = 0.8, Cgap = .5, Llab = "",
Rlab = "", Clab = "Title", GL = F, Lcol = "blue", Rcol = "blue",
Ldens = -1, main = "Distribution of Levels")
#save the current printed plot
pyrPlot<-recordPlot()
#plot it again
pyrPlot
You might have to enable the displaylist using dev.control(displaylist ="enable") for this to work depending on the graphical device you are using