Home | News | Documentation | Download

Problems with generating a 2D histogram from a text file

Hi, I have a text file with 2 columns and I want to plot all the data in a TH2D. I wrote some code for it but for some reason I am getting a completely blank document. Not even the axis are showing up. I want the first column to be plotted on the y-axis and the second column on the x-axis. Here is my code:

#include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <map>
#include <vector>

void plot()
{

  TH2D *h1 = new TH2D("h1", "All Nuclei", 100, 0, 100, 100, 0, 100);
  h1->GetXaxis()->SetTitle("Neutrons");h1->GetXaxis()->CenterTitle();
  h1->GetYaxis()->SetTitle("Protons");h1->GetYaxis()->CenterTitle();

  ifstream in("All_Zr.txt");
  std::vector<std::pair<int, int>> vec;
  int N, Z;
  while(in >> Z && in >> N){
    h1->Fill(N, Z);
  }

  TCanvas *c1 = new TCanvas();
  h1->Draw("colz");
  c1->Print("plots/plot_Zr.pdf[");
  c1->Print("plots/plot_Zr.pdf]");
}

May be N and Z are out of the range. They should be between 0 100 according to the limits you defined for your histogram. If you post your txt file we will be able to help more.

N and Z should not be out of range. Here is the text file:
Example.txt (729 Bytes)

The actual file was too large so I copied some of it and made this.

For multi-page PDF, use “(” and “)”, not square brackets.
https://root.cern.ch/doc/master/classTPDF.html

{
  auto *h1 = new TH2D("h1", "All Nuclei", 100, 0, 100, 100, 0, 100);
  h1->GetXaxis()->SetTitle("Neutrons");h1->GetXaxis()->CenterTitle();
  h1->GetYaxis()->SetTitle("Protons");h1->GetYaxis()->CenterTitle();

  ifstream in("Example.txt");
  std::vector<std::pair<int, int>> vec;
  int N, Z;
  while (in >> Z && in >> N) h1->Fill(N, Z);

  TCanvas *c1 = new TCanvas();
  h1->Draw("colz");
  c1->Print("Example.pdf")
}

Example.pdf (14.6 KB)