Search code examples
c++unicoderoot-framework

ROOT(CERN): How to draw a figure with title in unicode


I'm trying to draw a scatter figure via root-framework(cern). I want to set the titles of the figure in chinese, but I failed. My code for setting the title is

TGraphErrors graph(x,y,x_err,y_err);
char title[]=u8"圖表標題;x座標;y座標";//chinese title
graph.SetTitle(title);

But in the figure, all the titles are shown in garbled text as shown in the following picture shown:

figure with garbled text

Also, if I use a unicode string(i.e. wchar_t title[]=L"圖表標題;x座標;y座標"), I will get an error since graph.SetTitle() doesn't support that. But all strings above can show properly in the standard input/output in the terminal. So it seems that the question is not the string contains chars with wrong encoding, but root-framework can't perform them properly. Is there any way to show unicode in the figure?

p.s. I run the code by root code.cpp and compile it with g++, but the results are the same. My root's version is 6.26/02 and my OS version is Ubuntu 22.04.

p.s. Also, if there is a solution for both way of building the code (compiled by g++ or use as a root marco),it will be great.


Solution

  • There is a dirty hack: instead of providing Chinese characters via TGraph::SetTitle(), you can place TMathText instances wherever you want your characters to appear:

        gStyle->SetOptTitle(0); // no graph title please, we'll create our own
    
        double x1[5]{0., 1., 2., 3., 4.}, y1[5]{1., 2., 3., 4., 5.};
        TGraph* graph_one = new TGraph(5, x1, y1);
        graph_one->Draw("AP");
    
        (new TMathText(2.0, 5.5, "\\hbox{圖表標題}"))->Draw(); // graph title
    
        TMathText l_x; // x-axis title
        l_x.DrawMathText(4.0, 0.2, "\\hbox{x座標}");
    
        TMathText l_y; // y-axis title
        l_y.SetTextAngle(90);
        l_y.DrawMathText(-0.3, 4.5, "\\hbox{y座標}");
    

    example of a TGraph with Chinese characters in the TGraph title and in the axes titles