swiftchartspie-chartswiftcharts

Add legend text to pie chart Swift Charts


I'm trying to add a legend to my chart, bu its only colours that are coming up without the text. I cant figure out why this is? To create my chart I use:

func configure (dataPoints: [String], values: [Double]) {
    chartIMG.noDataText = "Please Insert Some Data!"

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(x: values[i], y: Double(i))
        dataEntries.append(dataEntry)


    }



    let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Symptoms")
    let pieChartData = PieChartData(dataSet: pieChartDataSet)
    chartIMG.data = pieChartData

    let noZeroFormatter = NumberFormatter()
    noZeroFormatter.zeroSymbol = ""
    pieChartDataSet.valueFormatter = DefaultValueFormatter(formatter: noZeroFormatter)

    var colors: [UIColor] = []

    for i in 0..<dataPoints.count {
        let red = Double(arc4random_uniform(256))
        let green = Double(arc4random_uniform(256))
        let blue = Double(arc4random_uniform(256))

        let color = UIColor(red: CGFloat(red/255), green: CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)
        colors.append(color)
    }


    chartIMG.highlightPerTapEnabled = false
    chartIMG.usePercentValuesEnabled = false
    chartIMG.drawEntryLabelsEnabled = true
    chartIMG.centerText = "%"


    let legend = chartIMG.legend
    legend.font = UIFont(name: "Arial", size: 11)!
    legend.textColor = UIColor.black
    legend.form = .circle

    chartIMG.animate(xAxisDuration: 2, yAxisDuration: 2)

    pieChartDataSet.colors = colors
    pieChartDataSet.selectionShift = 0
    pieChartDataSet.sliceSpace = 2.5


}

I'm trying to achive something similar to: https://i.sstatic.net/eiSnN.png but cant seem to get the legend to display with the labels. Any idea why this is? I think it may be a simple line of code but I cant seem to find anything that works.


Solution

  • Simple answer if anyone is looking for this help:

     let dataEntry1 = PieChartDataEntry(value: Double(i), label: dataPoints[i], data:  dataPoints[i] as AnyObject)
    

    Answered here: https://stackoverflow.com/a/42234117/9397533