TH1: barOffest do not affect error bars

Hi!

I need to reduce the width and change the offset of the bins of a TH1. I also need to plot error bars (only the vertical bar) of each bin.

This is what I get:

canvas

The error bar is decentered respect to the bin it belongs to. How do I fix it so that the error bar lies on the bin vertical axis?

This is the macro I wrote on which I hope to get some help:

TCanvas *  test() {
	vector<Double_t> x = {0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
	vector<Double_t> y = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
	vector<Double_t> dy = {0.2, 0.2, 0.2, 0.2, 0.2, 0.2};
	
	gStyle->SetOptStat(false);
	gStyle->SetErrorX(0);
	TCanvas * canvas = new TCanvas("canvas", "canvasName", 500, 400);
	TH1D * hist = new TH1D("test", "a test", 6, 1, 3);
	
	for (size_t i = 0; i < 6; i++) {
		hist->SetBinContent(i + 1, y[i]);
		hist->SetBinError(i + 1, dy[i]);
	}
	
	hist->SetBarWidth(0.3);
	hist->SetBarOffset(0.6);
	
	hist->Draw("bars e0");
	
	return canvas;
}

Thank you!

Yes, that’s true, the bar offset applies on bars only.

Some suggestion on how to go around this?

It looks like that there’s a workaround for this, since the picture in the first post here Custom vertical error bars histogram seems exactly what I’m looking for.

The post you are pointing to does not seem to use any bar offset. At least not explicitly. The question is different from yours.
The error bars for histograms are painted at the bin center.
My first though would be to use a TGraphErrors to paint the error bar where you want.
May be somebody else will have a better idea.

1 Like

Yeah. That works. :thinking:

TCanvas *  test() {
	vector<Double_t> x = {0.5, 1.0, 1.5, 2.0, 2.5, 3.0};
	vector<Double_t> y = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
	vector<Double_t> dy = {0.2, 0.2, 0.2, 0.2, 0.2, 0.2};
	
	gStyle->SetOptStat(false);
	gStyle->SetErrorX(0);
	TCanvas * canvas = new TCanvas("canvas", "canvasName", 500, 400);
	TH1D * hist = new TH1D("test", "a test", 6, 1, 3);
	TGraphErrors * graph = new TGraphErrors("graph", "a graph");
	
	double offset = 0.5;
	double barWidth = 0.3;
	
	for (size_t i = 0; i < 6; i++) {
		hist->SetBinContent(i + 1, y[i]);
		graph->SetPoint(i + 1, hist->GetBinLowEdge(i + 1) + hist->GetBinWidth(i + 1) * (barWidth / 2 + offset), hist->GetBinContent(i + 1));
		graph->SetPointError(i + 1, 0, dy[i]);
	}
	
	hist->SetBarWidth(barWidth);
	hist->SetBarOffset(offset);
	hist->SetFillStyle(3001);
	
	hist->Draw("bars");
	graph->Draw("E");
	
	return canvas;
}

canvas

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