[R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

Deramus, Thomas Patrick tder@mu@ @end|ng |rom p@rtner@@org
Thu Oct 6 17:49:11 CEST 2022


Truly appreciate it Bill.

Will try to make something more trimmed down in the future, but unfortunately have to admit I am more of an R neophyte than I would like to be.
________________________________
From: Joshua Ulrich <josh.m.ulrich using gmail.com>
Sent: Thursday, October 6, 2022 11:26 AM
To: Bill Dunlap <williamwdunlap using gmail.com>
Cc: Deramus, Thomas Patrick <tderamus using partners.org>; r-help using r-project.org <r-help using r-project.org>
Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet" despite grouping plot call

        External Email - Use Caution

On Thu, Oct 6, 2022 at 9:44 AM Bill Dunlap <williamwdunlap using gmail.com> wrote:
>
> Here is how you could have made an example that helpers could easily run.
> It also includes the fix.
>
> f <- function(print.it = FALSE) {
>    pdf(file.pdf <- tempfile(fileext=".pdf"))
>    series <- as.xts(setNames(sin(seq(0,10,by=.1)),
> seq(as.Date("2022-10-06"),by="weeks",len=101)))
>    p <- plot(series)
>    if (print.it) {
>        print(p)
>    }
>    sm_series_2 <- smooth(series / 2)
>    lines(sm_series_2, col="red")
>    abline(h=0.1, col="blue")
>    dev.off()
>    file.pdf
> }
> > f()
> Error in plot.xy(xy.coords(x, y), type = type, ...) :
>   plot.new has not been called yet
> > f(TRUE)
> [1]
> "C:\\Users\\willi\\AppData\\Local\\Temp\\Rtmp0wX7rO\\file34843df652c.pdf"
>
> If you remove the pdf() and dev.off() I think you will see that the added
> lines do not show up.  I think plot.xts fiddles with the coordinate system
> before and after it plots so that add-ons must be done in a special way.
>

plot.xts() waits until the plot is rendered before calculating the
coordinate system. That allows users to add multiple series that have
different values for the index (x-axis) and data (y-axis).

lines() doesn't show up in your example because it's called after the
plot is rendered, and it's not rendered again after they're added.
`sm_series_2` also needs to be an xts object, otherwise lines.xts() is
not dispatched.

title() and abline() need to be called after the plot is rendered
because they are standard graphics functions. I admit that's very
confusing... I'll see what I can do to fix that.

Here's a revised example that works for me:

f <- function(print.it = FALSE)
{
    pdf(file.pdf <- tempfile(fileext=".pdf"))
    series <- xts(sin(seq(0,10,by=.1)),
seq(as.Date("2022-10-06"),by="weeks",length.out=101))
    p <- plot(series)
    sm2 <- xts(smooth(series/2), index(series))
    lines(sm2, col="red")
    if (print.it) {
        print(p)
        title("Sine curve example")
        abline(h=0.1, col="green")
    }
    dev.off()
    file.pdf
}
f(TRUE)



> -Bill
>
> On Thu, Oct 6, 2022 at 12:42 AM Deramus, Thomas Patrick <
> tderamus using partners.org> wrote:
>
> > Hi Rolf.
> >
> > I followed your suggestion (though it's probably not as trimmed as it
> > could be), but the problem unfortunately persists.
> >
> > Does this make it any clearer or still too many moving parts to make sense
> > of?
> >
> > rm(list = ls(all.names = TRUE)) #will clear all objects includes hidden
> > objects.
> >
> > #Loads the packages
> > library(plyr)
> > library(dplyr)
> > library(ggplot2)
> > library(Kendall)
> > library(lubridate)
> > library(xts)
> > library(TTR)
> > library(trend)
> > library(forecast)
> > library(openxlsx)
> >
> > #Uses the learningCurve Package from Github:
> > #https://secure-web.cisco.com/1GC2a24rvTQn4ZsRD2yEzdiU8p0VcreF81tS2HTnyYa7VJF5IpO2yI1E7CRvAjkTDIaj6KEYqjTGRSAenLfIdC6jV3OEUiCZS17V58pTwQ-55guIdhru6Sek8uJuW1ts44qoo8ZbniSWEwzzch1DcQTxCe9raR3xZavXdeOins1Yzg7le2LJWuRBEk8s9CxpKUsKa9l3qmWmjRszIWVX7nZSBTjnNOFTcJgqc8MQu8qZojb4GwCZ8mlP7U4dQdClXlDxxlTL6kF-Awi1NmycuaWn8MYEjxDTpdyqw97MAkHjESJbjB7Hfv93No-E5_9cp/https%3A%2F%2Fgithub.com%2FAFIT-R%2FlearningCurve
> > library(learningCurve)
> >
> > #Only load this if using VS Studio because it changes the plot function
> > #
> > https://secure-web.cisco.com/19uRRA2OdQiP-LFePtct8U8sQ1opEP7PrOFLjX3GDTAREApng8FFteGdDY-n8lnkoclvIekYRw4YgvqG24Tsovdeq3hKnKx6iBpWoAy-tOijBFwH0AKBvugicSxwCStU9yZANYx2BTYDd8bYZoEkwTYnthGTH4AKLybu5ek_wJMX0hCEzx9IxjRZ-03ISDvocEUUspf4uxi841j1qW7mAZ3WMj4pjTUa8mlUznIxtkTeEdGYN0X4j3Q5iiwLin6l0gntobwjoaTMv_0kq8hQe6_cYJCxBVxU-CEYcY8KPjsM9YBC-oYeFhUt13Wqlj-mO/https%3A%2F%2Fstackoverflow.com%2Fquestions%2F52284345%2Fhow-to-show-r-graph-from-visual-studio-code
> > library(httpgd)
> > library(languageserver)
> >
> > #Loads the Excel files to Dataframes and cleans the data
> > Game_Metrics_Word_Task <-
> > read.xlsx("GamePack_Analytics_ALL_TIME_Short.xlsx", "Boggle")
> > Game_Metrics_Word_Task <- Game_Metrics_Word_Task %>% filter(grepl('1440',
> > StudyId))
> > Game_Metrics_Word_Task$DeviceTime <-
> > ymd_hms(Game_Metrics_Word_Task$DeviceTime,  tz = "America/New_York")
> > Game_Metrics_Word_Task <-
> > Game_Metrics_Word_Task[!duplicated(Game_Metrics_Word_Task[1:2,])]
> >
> > #Splits the dataframe into a tibble containing each participant
> > Participant_Word_Task <-
> > split(arrange(Game_Metrics_Word_Task,StudyId,DeviceTime),
> > arrange(Game_Metrics_Word_Task,StudyId,DeviceTime,StudyId,DeviceTime)$StudyId)
> >
> > #Generates a blank output dataframe
> > WordFrame <- data.frame(Participant = c(0), Task = c(0), MannKendall_Tau =
> > c(0), MannKendall_P = c(0), Sen_Slope_Value = c(0), Sen_Slope_Pval = c(0),
> > Pettitts_CIV = c(0), Pettitts_Pval = c(0), ARIMA_Model = c(0),
> > Time_to_Petit = c(0), Number_of_Trials_to_Pettitt = c(0),
> > Playtime_to_Petit_seconds = c(0), Time_Start_to_end_days = c(0),
> > Number_of_Total_Trials = c(0), Total_Playtime_seconds = c(0),
> > Learning_rate_days = c(0), Learning_rate_seconds = c(0), Learned_Task =
> > c(0))
> >
> > #The number of subjects in the xlsx file
> > #Reduced to 2 for ease of use
> > for (i in 1:2){
> >   #This timeseries only includes the trials where the participant
> > completed the task
> >   success_series <- xts(filter(Participant_Word_Task[[i]], GameEndReason
> > == "TIMER_UP")$NumberOfSuccesfulWords , order.by=as.POSIXct(filter(Participant_Word_Task[[i]],
> > GameEndReason == "TIMER_UP")$DeviceTime))
> >   #This timeseries includes ALL the trials for the sake of plotting
> >   original_series <-
> > xts(Participant_Word_Task[[i]]$NumberOfSuccesfulWords, order.by
> > =as.POSIXct(Participant_Word_Task[[i]]$DeviceTime))
> >
> >   #This is a decomposing process that xts seems to need for plotting.
> >   #nweeks is needed for xts to plot the x-axis
> >   success_decomp <- ts(success_series, frequency = nweeks(success_series))
> >   original_decomp <- ts(original_series, frequency =
> > nweeks(success_series))
> >
> >   #Values which will be included in the plots
> >   WordFrame[i,1] <- unique(Participant_Word_Task[[i]]$StudyId)
> >   WordFrame[i,5] <- sens.slope(success_decomp)$estimates
> >   WordFrame[i,6] <- sens.slope(success_decomp)$p.value
> >   WordFrame[i,7] <- pettitt.test(success_decomp)$estimate
> >   WordFrame[i,8] <- pettitt.test(success_decomp)$p.value
> >
> >   #The simple moving average that will be overlayed with the plotted data
> >   simplemovingaverage <- SMA(original_series, n = nweeks(original_series))
> >
> >   #If the three tests are statistically significant, add a green
> > horizontal like to value WordFrame[i,7]
> >   #Which would be where the slope changes in the series
> >   #Fluid variables have been removed from all pdf() and paste() functions
> > for ease-of-use
> >   if (WordFrame[i,4] <= 0.05 & WordFrame[i,6] <= 0.05 & WordFrame[i,8] <=
> > 0.05){
> >      {
> >       pdf(file = "Word_Task_Acquisition.pdf")
> >       plout <- plot(original_series)
> >       lines(simplemovingaverage)
> >       abline(v = index(original_series[WordFrame[i,7]]),lty=2,
> > col='green', lwd=3)
> >       title(paste("Word Task Acquisition for Subject"))
> >       dev.off()
> >      }
> >   #If the three tests are NOT statistically significant, generate a plot
> > with NO horizontal line at WordFrame[i,7]
> >   } else {
> >     {
> >       pdf(file = "Word_Task_Acquisition.pdf")
> >       plout <- plot(original_series)
> >       lines(simplemovingaverage)
> >       title(paste("Word Task Acquisition for Subject"))
> >       dev.off()
> >     }
> >   }
> > }
> >
> > ________________________________
> > From: Rolf Turner <r.turner using auckland.ac.nz>
> > Sent: Wednesday, October 5, 2022 6:06 AM
> > To: Deramus, Thomas Patrick <tderamus using partners.org>
> > Cc: r-help using r-project.org <r-help using r-project.org>
> > Subject: Re: [R] Getting "Error in ect, plot.new has not been called yet"
> > despite grouping plot call
> >
> >         External Email - Use Caution
> >
> > What you doing or trying to do is far too complex for my poor feeble
> > and senile brain to come anywhere near comprehending.  The code that
> > you present exceeds my complexity tolerance by many orders of magnitude.
> >
> > I have a suggestion, but.  Strip your code down to the *essentials*.
> > Construct a simple sequence of plotting commands, with *simple* names
> > for the pdf files involved.  You should require only two or three such
> > files and two or three index levels associated with each of your
> > nested loops.
> >
> > Run the stripped down code and the source of the problem will almost
> > surely become clear.
> >
> > cheers,
> >
> > Rolf Turner
> >
> > On Tue, 4 Oct 2022 23:35:09 +0000
> > "Deramus, Thomas Patrick" <tderamus using partners.org> wrote:
> >
<snip>
> > > �Issac Asimov
> >
> > The information in this e-mail is intended only for th...{{dropped:22}}
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://secure-web.cisco.com/1SgVzv3MhZxjS8lVtL-AremtzH9si_AP6nzXeP88cMer7WPpSbOcW6bQxA1_OS8tZfnCR4A2dnkLji0Xp6WSmRSij8pKrLyRC88Hs_VerYcbpwTmmsgMvWy-fJqib7KS0Pe3sz6uw8bjRWL1kqrus4AEumxFWNkTUdne-TFZJSuNOREO0uZ2-TQIu-Xb6N4Dts3snQ7ChYqiEZbiv009G2CofS-41urHFmbmtfEXay8g9SlLFflx1YVNoU2VK8lToEb-0BFCetotnxGlK_wLqGKAF11eE4HGUA_uZuBHB9zwWAiNpEPZ0RaZ5oleTjlRY/https%3A%2F%2Fstat.ethz.ch%2Fmailman%2Flistinfo%2Fr-help
> PLEASE do read the posting guide http://secure-web.cisco.com/128DnoUBGpXNKPpn-_IIbo2_5a9sLNJXREjbFp3cT2Ho_IxpgACzE8mFRNc3SzHQtfOzJ7UGe-7kbG4pMAw6xbxdx5U0P4WtBPr4etT4P1F4zmWvXwthbNt1gleb4i2WNnIXgrne6n5jGt0Aj3mZCVuUft56CCVyopOOVaA-8O093biCfDFWuT2Mgi0UZC6jKiUoBb4jpGoAwrvWIt8BatRnhER5zyL4EeEjR4Hztxlw0sdOQX71AT7bclT9UtV7ZcYPpCw8MSPYNEXd2rUIeYqbPaYwwLJYIfhpMCq2fimy6N1BLxClytQzF1IUo77Rv/http%3A%2F%2Fwww.R-project.org%2Fposting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



--
Joshua Ulrich  |  about.me/joshuaulrich
FOSS Trading  |  http://secure-web.cisco.com/1a6xFSrjm-kcAD3kFpY-MqFccS9tOSo60B0iS6Vc-3YL2jcoq-n2LgKPqVzbQ5ir8uo_2QTYF5GdGxAAniCa47MXagKCxQLoHf-QDEpHuk0HUSvYaXhf3mMKt6FA9Gyao_ZDezq8FCdAeyqdDbuf2UpRQWX7h6AlgMfRZgoxY1j7cr15jkXNPjs7nR9Jr6S5VH37YmzyrbIfBlYqY2rIPUt2BgnyqUDbXknZbB2JVHKw5giicByw9dzXuIhiEm357Wjcy5vwCvn8BuoAuymq17BRKc98dGSO1cbflw94gPWR5m8x6kZq1sa-Li8l7BB62/http%3A%2F%2Fwww.fosstrading.com
The information in this e-mail is intended only for the ...{{dropped:15}}



More information about the R-help mailing list