// This macro extracts the contour lines (TGraphs) from // 2 dim histogram and draws them together with labels // onto a copy the histogram // the position of the label is arbitrary choosen to be // point 0 of the graph void gen_contours(TH2 *hin = NULL, Int_t nlevels = 5) { // if (!h2 || !h2->InheritsFrom("TH2") return; TH2 *h2 = hin; if (!h2){ h2 = new TH2F("h2","h2", 40, -4, 4, 40, -4, 4); Double_t x, y; Int_t i = 0; while(i++ < 100000) { gRandom->Rannor(x,y); h2->Fill(x,y); // try this to make it look more realistic //h2->Fill(x-1.5,y+1); //if (i%2 == 0) h2->Fill(1.5*x+1,y-1); } h2->Smooth(); // make contours look smoother/nicer } auto can = new TCanvas("can","For h2",50,100,600,600); h2->SetContour(nlevels); h2->Draw("CONT Z LIST"); // generate a list with TGraphs can->Update(); // force drawing TObjArray *lofconts = (TObjArray*)gROOT->GetListOfSpecials()->FindObject("contours"); if (!lofconts) return; auto cancon = new TCanvas("cancon","For contours",730,100,600,600); TString fname(h2->GetName()); fname +="_contours.root"; // auto outfile = new TFile(fname, "RECREATE"); auto hclone = (TH2*)h2->Clone(); hclone->Draw("COL Z"); TList *lofgraphs; TGraph *graph; Int_t nconts = lofconts->GetSize(); Double_t *clevels = new Double_t[nconts]; h2->GetContour(clevels); Double_t xp, yp; TLatex *label; // loop on contours for (Int_t ic =0; ic < nconts; ic++) { // get list of graphs lofgraphs = (TList*)lofconts->At(ic); if (!lofgraphs) return; Int_t ngraphs = lofgraphs->GetSize(); if (ngraphs == 0) continue; // Note: their might be several closed lines on same level // loop on graphs for (Int_t ig =0; ig < ngraphs; ig++) { graph = (TGraph*)lofgraphs->At(ig); if (!graph) return; // outfile->cd(); // graph->Write(); cancon->cd(); graph->Draw("c"); // get x, y of 1. point and put label graph->GetPoint(0, xp, yp); label = new TLatex(xp, yp, Form("%.1f", clevels[ic])); label->SetTextSize(0.02); label->Draw(); } } // if (outfile) outfile->Write(); }