Search code examples
wxwidgets

How to change the serie colur and pen in wxFreeChart?


I am using wxFreeChart library in my project. However I am unable to change the colour and line type in XY data series. In the documentation nor in the samples there is no example of such functionality. Also there are not straightforward functions allowsing to do this. Does anyone has experience with this library to say if it is even possible?


Solution

  • Yes, it is possible to set both the serie colour and the pen type for XY line charts.

    These attributes are set via the XYLineRenderer class. The documentation does cover this but you have to click on the "List all members" to see them. The current documentation is available under XYLineRenderer Members.

    For simple changes, you can access the XYLineRenderer using the XYDataset::GetRenderer() method. This returns an XYRenderer* which you will need to cast to a XYLineRenderer* in order to set the pen type. Of course you can create the XYLineRenderer* first and pass it to the XYDataset::SetRenderer method instead.

    Here is an example:

    // Set the colour and pen of the first series.
    static_cast<XYLineRenderer*>(dataset->GetRenderer())
                    ->SetSeriePen(0, new wxPen(*wxRED, 5, wxPENSTYLE_SHORT_DASH));
    
    // Set the colour and pen of the second series.
    static_cast<XYLineRenderer*>(dataset->GetRenderer())
                    ->SetSeriePen(1, new wxPen(*wxBLUE, 1, wxPENSTYLE_DOT_DASH));
    

    SetSeriePen is only available to XYLineRenderer for obvious reasons, but you can set the colour of any renderer with Renderer::SetSerieColour(size_t serie, wxColour *color).

    Note: I am not that happy with the way wxFreeChart takes pointers in these functions. This project is not actively maintained, but I would like at some point to fork it and update the API to be more consistent with modern versions of C++ and wxWidgets.