How to form a Color_t from a TColor

Hello,

I want to draw a few histograms on top of each other, with different colors.
I need a general way to color each histogram (with an unknown number of histograms), with the color wheel, so that they are all evenly spaced out across the whole color wheel.
The problem is that SetLineColor only receive a Color_t type, and setting the RGB requires TColor.
How shall I go about that?

thanks.

You can use a new feature in ROOT 6.10 (already available in ROOT 6.09.01), which allows automatic coloring of plots from the current palette:

New options for automatic coloring of graphs and histograms. When several histograms or graphs are painted in the same canvas thanks to the option “SAME” via a THStack or TMultigraph it might be useful to have an easy and automatic way to choose their color. The simplest way is to pick colors in the current active color palette. Palette coloring for histogram is activated thanks to the options PFC (Palette Fill Color), PLC (Palette Line Color) and PMC (Palette Marker Color). When one of these options is given to TH1::Draw the histogram get its color from the current color palette defined by gStyle->SetPalette(…). The color is determined according to the number of objects having palette coloring in the current pad.

You can find the complete documentation of this feature here: ROOT: TGraphPainter Class Reference

You can either define a custom color palette or use a pre-defined one. Have a look at the documentation:
https://root.cern.ch/doc/master/classTColor.html#C05


Alternatively, if you are using pyROOT, you can write a class that wraps around Color_t, which you can use to initialize arbitrary colors:

import ROOT


class Color(int):
    """Create a new ROOT.TColor object with an associated index"""
    __slots__ = ["object", "name"]

    def __new__(cls, r, g, b, name=""):
        self = int.__new__(cls, ROOT.TColor.GetFreeColorIndex())
        self.object = ROOT.TColor(self, r, g, b, name, 1.0)
        self.name = name
        return self


colors = [Color(0, 0, 0, "black"),
          Color(0.9, 0.6, 0, "orange"),
          Color(0.35, 0.7, 0.9, "skyblue"),
          Color(0, 0.6, 0.5, "bluishgreen"),
          Color(0, 0.45, 0.7, "blue"),
          Color(0.8, 0.4, 0, "vermillion"),
          Color(0.8, 0.6, 0.7, "reddishpurple")]
for color in colors:
    setattr(ROOT, color.name, color)

These colors can afterwards be accessed like any other color in pyROOT (so e.h. h.SetLineColor(ROOT.vermillion)). This works, because this class holds the color object, but to the outside it looks like an int (with its value being the index in ROOTs color table).

2 Likes

As it seems you are using histograms you can look at:
https://root.cern.ch/doc/master/classTHistPainter.html#HP061
It is very similar to the page @Graipher mentioned.

1 Like

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