Draw multiple graphs/histograms with automatic color palette marker/line colors

When I’m looking into time dependencies of my data, I like to plot multiple graphs or histograms for different time frames inside the same TPad. As far as I know, all objects of a certain type drawn inside a pad are assigned the same default color. To be able to differentiate between them meaningfully, I assign them colors according to a color palette.

Is there a way for the TPad to automatically assign colors to its plotted members? Right now, I’m assigning colors before drawing for each object on its own, like shown in the code below. I’d like to just be able to save the canvas without specifying the members’ colors, but getting the color palette when opening the canvas later on. Setting and forcing a custom style in the rootlogon.C does not have the desired effect.

On the matter of graphs I know about TMultiGraph but it doesn’t seem to assign colors by itself.

This is a simplified version of what I’m doing at the moment

TCanvas* overlaid_histograms(const std::vector<TH1F*>& histos,
                             const std::string& canvasName, const double colorPalette)
{
    gStyle->SetPalette(colorPalette);
    int nColors = gStyle->GetNumberOfColors();
    int nHistos = histos.size();

    TCanvas* cOut = new TCanvas(canvasName.c_str(), canvasName.c_str());
    for (size_t i = 0; i < nHistos; ++i) {
        int histoColor = (float)nColors / nHistos * i;
        histos[i]->SetLineColor(gStyle->GetColorPalette(histoColor));
        if (i == 0) {
            histos[i]->Draw();
        } else {
            histos[i]->Draw("same");
        }
    }
    cOut->BuildLegend();

    return cOut;
}

Thanks!

1 Like

Yes this functionality has been recently implemented.
You can see examples here:

https://root.cern/doc/master/classTHistPainter.html#HP061
https://root.cern/doc/master/classTGraphPainter.html#GP05
https://root.cern/doc/master/classTMultiGraph.html
https://root.cern/doc/master/thstackpalettecolor_8C.html
https://root.cern/doc/master/classTHStack.html

1 Like

Thanks! Lucky me that it was released only last month. :slight_smile:

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