Issue converting argument for TGraph in PyROOT

Hi, I am trying to write a macro using PyROOT that ultimately produces a canvas containing multiple TGraphs, however I am running into an issue whereby a get an error with converting arguments. More specifically

TypeError: void TGraph::SetPoint(int i, double x, double y) =>
    could not convert argument 2 (a float is required)

I understand from this thread that arguments for TGraphs need to be C-style arrays, specifically numpy arrays. Initially I had been using non-numpy arrays (which had worked for me in the past in other PyROOT applications), for example array('d'), and I hoped that simply changing these to numpy arrays with np.array(x) but that didn’t work and produced the error

TypeError: void TGraph::SetPoint(int i, double x, double y) =>
    could not convert argument 2 (only length-1 arrays can be converted to Python scalars)

I’ve attached a test example below that gives the first error.

import ROOT
from ROOT import TChain, TFile, TTree, TSelector, TGraph, TGraphErrors
from ROOT import gROOT
import numpy as np
from array import array

values_dict = {}
x = array('d') 
plots_dict = {}

for i in range (0,2):
    
    values_dict["%s_values"% (i)] = array('d')
    plots_dict["%s_plot"% (i)] = ROOT.TGraph()
    x.append(i)
    for j in range (0,3):
        values_dict["%s_values"% (i)].append(j)

c1 = ROOT.TCanvas("c1","",1200,600)
for n in range(0,2):
    ROOT.c1.cd(n+1)
    plots_dict["%s_plot"% (n)].SetPoint(2,x,values_dict["%s_values"% (n)])
    plots_dict["%s_plot"% (n)].Draw('AP')

Alternatively the penultimate line can be changed to

plots_dict["%s_plot" %(n)].SetPoint(2,np.array(x),np.array(values_dict["%s_values" %(n)]))

to give the second error.

Any advice on how to solve this would be much appreciated

It seems you are using SetPoint. SetPoint takes simple float values as input not arrays.

Thanks for the reply! Yes you’re quite right. I got far too wrapped up in worrying about the different objects ROOT would accept in Python vs C++ and lost sight of what I was actually doing.

The issue in this case was fixed by simply changing the penultimate line in the code above to

plots_dict["%s_plot" %(n)] = ROOT.TGraph(2,np.array(x),np.array(values_dict["%s_values" %(n)]))

Thanks for the help

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.