Pyroot script crashes when adding second axis

Hello!
I have this simple Python script, however it crashes when I try to add a secondary x axis. The canvas gets somehow deleted after the TGaxis::Draw command.

TypeError: void TPad::SaveAs(const char* filename = "", const char* option = "") =>
    TypeError: callable was deleted

Any idea what I might be doing wrong?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import numpy as np
from ROOT import TFile, TTree, TCanvas, TH1D, TLegend, TF1, TGaxis, TGraph, TLine, gStyle, gPad, gROOT, kBlack, kRed, kBlue, kGreen, kOrange, kMagenta, kViolet, kCyan, kRed, kBlue,  kYellow

hustart = [-1024, -975, -925, -875, -825,
           -775, -300, -250, -200, -150,
           -100, -75, -50, -25, 0,
           15, 25, 40, 60, 75,
           90, 130, 170, 200, 230,
           260, 295, 330, 360, 390,
           420, 450, 480, 510, 540,
           570, 595, 625, 650, 680,
           3072]

humed = [(hustart[i-1] + hustart[i])/2. for i in range(1,len(hustart))]
matids = [i-1 for i in range(1,len(hustart))]

mat2hu = TGraph(len(matids), np.asarray(matids,'d'), np.asarray(humed,'d'))

c = TCanvas('Attenuation')
c.SetGridx()
c.SetGridy()
h = TH1D('h','',40,-0.5, 39.5)
h.SetBinContent(2, 4)
h.Draw()

c.Modified()
c.Update()

def myfunc(x):
    val = mat2hu.Eval(x[0])
    return val

myfunc = TF1("myfunc",myfunc,0,39)
A1 = TGaxis(0,gPad.GetUymax(),39,gPad.GetUymax(),"myfunc",515,"-")
A1.Draw()

c.SaveAs('/tmp/'+c.GetName()+'.png')

using:

   ------------------------------------------------------------------
  | Welcome to ROOT 6.25/01                        https://root.cern |
  | (c) 1995-2021, The ROOT Team; conception: R. Brun, F. Rademakers |
  | Built for linuxx8664gcc on Sep 01 2021, 23:19:42                 |
  | From heads/master@v6-25-01-1861-g6b33e04cac                      |
  | With c++ (Ubuntu 8.4.0-1ubuntu1~18.04) 8.4.0                     |
  | Try '.help', '.demo', '.license', '.credits', '.quit'/'.q'       |
   ------------------------------------------------------------------

it must be a python issue because a C reduced version of your script works fine:

{
   auto c = new TCanvas("Attenuation");
   c->SetGridx();
   c->SetGridy();
   auto h = new TH1D("h","",40,-0.5, 39.5);
   h->SetBinContent(2, 4);
   h->Draw();

   auto A1 = new TGaxis(0,gPad->GetUymax(),39,gPad->GetUymax(),"myfunc",515,"-");
   A1->Draw();

   c->Print("a.png")
}

Yes, maybe I am not defining well the def myfunc function or mat2hu has to be made a global variable? I normally use C++, so if anyone with more experience with Python can help with this, I would appreciate it :slight_smile:

Ok, I managed to fix it, by changing the following:

myfunc2 = TF1("myfunc",myfunc,0,39)

and:
def myfunc(x,p):