How to set different color of text for the legends using core plot

544 views Asked by At

I am using core plot to for drawing the graph. My problem is i want to set the legends text color according to line color. I have four scatter plot in one graph, each scatter plot is having different line color.

In the legends it will show line color correctly but i want to change the text color according to line color for each scatter graph title. I have written the following code for the legend.

newGraph.legend = CPTLegend(graph: newGraph)
        newGraph.legend?.numberOfRows = UInt(2.0)
        let dataSourceLabelStyle = CPTMutableTextStyle()
        dataSourceLabelStyle.color = CPTColor.white()
        newGraph.legend?.textStyle       = dataSourceLabelStyle
        newGraph.legend?.fill = CPTFill(color: CPTColor.init(componentRed: 50/244, green: 43/244, blue: 87/244, alpha: 1.0))
        newGraph.legend?.cornerRadius = 5.0
        newGraph.legendDisplacement = CGPoint.init(x: -50, y: 210)
        let fadeInAnimation = CABasicAnimation(keyPath: "opacity")
        fadeInAnimation.duration            = 1.0
        fadeInAnimation.isRemovedOnCompletion = false
        fadeInAnimation.fillMode            = kCAFillModeForwards
        fadeInAnimation.toValue             = 1.0
        dataSourceLinePlot.add(fadeInAnimation, forKey: "animateOpacity")
        self.scatterGraph = newGraph

as form the above code it is seen that legends can take only one style i.e newGraph.legend?.textStyle = dataSourceLabelStyle so all the text in the legends is of white color.

I want to change the legends text color also according to line color.

Can any body help me with this.

2

There are 2 answers

0
Eric Skroch On BEST ANSWER

For most plot types including scatter plots, set the attributedTitle to an NSAttributedString with the desired color attributes. Pie charts and bar plots have datasource methods to provide attributed legend titles for each data index.

0
Boris Gafurov On

Do not think it is possible cause you set the legend for the graph and graph contains all your plots. Here is how I am using it in ObjC though:

CPTScatterPlot *aPlot = [[CPTScatterPlot alloc] init];
    aPlot.dataSource = self;
    aPlot.identifier = stringPlotId;
    [graph addPlot:aPlot toPlotSpace:plotSpace];   
 aPlot.title=stringPlotTitle;//will show in legends

 //add more plots if needed then format labels text once for all plots

graph.legend= [CPTLegend legendWithGraph:graph];
CPTMutableTextStyle *mySmallerTextStyle = [[CPTMutableTextStyle alloc] init];
[mySmallerTextStyle setFontSize:8];
mySmallerTextStyle.color=[CPTColor whiteColor];
[graph.legend setTextStyle:(CPTTextStyle *)mySmallerTextStyle];