Draw a grid for a graph (python)

im trying to draw a grid for my graph, seen below. I know I can use ROOT.gPad.SetGrid(1, 1) but it doesnt let me decide on the grid location. I would like a line (vertical and horizontal) to go through every blue dot.

This is my code (along with @couet 's suggestion):


c = TCanvas(name)
    c.Divide(2, 1)

    before = TGraph(len(x), x, y)
    before.SetMarkerStyle(1)
    before.SetMarkerColor(ROOT.kBlue)
    before.SetMarkerSize(1)
    before.SetTitle("Before")
    c.cd(1)
    before.Draw("AP")
    Grid = TH2C("Grid", "Grid", 10, -10., 10., 10, 20., 40.)
    Grid.SetStats(0)
    Grid.GetXaxis().SetNdivisions(-20)
    Grid.GetYaxis().SetNdivisions(-20)
    Grid.Draw("SAME")
    # ROOT.gPad.SetGrid(1, 1)
    # ROOT.gPad.Update()
    c.SetGrid()
    c.Draw()

    after = TGraph(len(a), a, b)
    after.SetMarkerStyle(1)
    after.SetMarkerColor(ROOT.kRed)
    after.SetMarkerSize(1)
    after.SetTitle("After")
    c.cd(2)
    # ROOT.gPad.SetGrid(1, 1)
    # ROOT.gPad.Update()
    c.SetGrid(1, 1)
    after.Draw("AP")
    c.Draw()

This macro does it:

{
   TCanvas *c1 = new TCanvas("c1","c1",10,10,800,800);
   gStyle->SetGridStyle(1);
   TH2C *Grid = new TH2C("Grid","Grid",10,-10.,10.,10,20.,40.);
   Grid->SetStats(0);
   Grid->GetXaxis()->SetNdivisions(-20);
   Grid->GetYaxis()->SetNdivisions(-20);
   Grid->Draw();
   c1->SetGrid();
}

@couet this doesnt work.

also, why do i need both the histogram and c.SetGrid()? what does SetGrid() does and what does it have to do with the histogram?

can you be more precise ???

The histogram is used to draw the axis and user coordinates. The grid is an attribute of the canvas holding the histogram.

@couet its seems to have no afffect on the pitcure. How would you suggest to combine you’re code with mine?

how does SetGrid knows which histogram to pick?

I guess you saw that my macro draws the grid you are asking for ? right ? running only my macro should be fine. Now it could be that the way you combined it with your code is wrong. So yes I would need a macro reproducing what you get to help you further. (note that I am soon on holidays, better solve this today).

I saw you modified your first post with some example. Vectors x,y,a and b are missing though .

It does not need to know. SetGrid sets a flag at the canvas level. When the histogram is drawn this flag is checked … as simple as that …

This macro: ofirar.C (1010 Bytes)

Produces:

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