Set User defined Palette of 2D histogram

try this and play with colors and bias etc.

#include "TStyle.h"
#include "TCanvas.h"
#include "TH2.h"
#include "TRandom.h"

void testgl()
{
// gStyle->SetCanvasPreferGL(kTRUE);
   TCanvas *cc= new TCanvas();
   TH2F* h2 = new TH2F("h2", "h2", 50,-10,10, 50,-10,10);
   Double_t x,y;
   Int_t n = 100000;
   while (n-- > 0) {
      gRandom->Rannor(x,y);
      h2->Fill(x,y);
   }
   // fix color below bias
   Int_t bias = 0.5 * h2->GetMaximum();
   
   const Int_t Number = 3;
   Double_t Red[Number]    = { 1.00, 0.00, 0.00};
   Double_t Green[Number]  = { 0.00, 1.00, 0.00};
   Double_t Blue[Number]   = { 0.00, 0.00, 1.00};
   Double_t Length[Number] = { 0.00, 0.50, 1.00 };
   const Int_t nlevels = 50;
   Int_t MyPalette[nlevels];
   Int_t FI = TColor::CreateGradientColorTable(Number,Length,Red,Green,Blue,nlevels);
   for (int i=0;i<nlevels;i++) MyPalette[i] = FI+i;
   
   Double_t clevels [nlevels];
   // between 0 and bias color should be kWhite
   clevels[0] = 0;
   clevels[1] = bias;
//   MyPalette[0] = kBlack;
   MyPalette[0] = kWhite;
   // the rest continous
   Double_t dz =  (h2->GetMaximum() - bias) / (Double_t)(nlevels-2);
   for (Int_t k=2; k < nlevels; k++) {
      clevels[k] = bias + (k-1)* dz;
   }
   h2->SetContour(nlevels, clevels);
   gStyle->SetPalette(nlevels, MyPalette);
// h2->Draw("SURF1");
   h2->Draw("LEGO2 0"); // dont draw empty bins
// h2->Draw("LEGO2GL");
}

Cheers
Otto

1 Like