Search code examples
swiftios-charts

Get rid of text 'DataSet' in pieChart legend


So, I've created a vc with a pieChart. The legend of the pieChart shows the word 'DataSet' behind it. It's not something I've deliberatly put in... Where does it come from, how do I get rid of it?

enter image description here

Here's my pieChart code:

fileprivate func setupPieChart() {
    let titleParagraphStyle = NSMutableParagraphStyle()
    titleParagraphStyle.alignment = .center

    let attributedCenterText = NSAttributedString(string:"Number of Reports", attributes:
        [NSAttributedString.Key.foregroundColor: Settings.shared.currentTheme.textColor, NSAttributedString.Key.paragraphStyle: titleParagraphStyle])

    self.pieChartView.backgroundColor = .clear
    self.pieChartView.centerAttributedText = attributedCenterText
    self.pieChartView.drawEntryLabelsEnabled = false
    self.pieChartView.highlightPerTapEnabled = false
    self.pieChartView.holeColor = .clear
    self.pieChartView.legend.textColor = Settings.shared.currentTheme.textColor
    self.pieChartView.usePercentValuesEnabled = false
}

fileprivate func setupPieChartData() {
    let dataSet = PieChartDataSet()
    dataSet.colors = ChartColorTemplates.material()
    dataSet.valueColors = [Settings.shared.currentTheme.textColor]

    for key in self.data.keys.sorted() {
        if let team = self.teamService.team(for: key), let reportCount = self.data[key]?.count {
            let entry = PieChartDataEntry(value: Double(reportCount), label: team.teamName)
            dataSet.append(entry)
        }
    }

    let data = PieChartData(dataSet: dataSet)

    let formatter = NumberFormatter()
    formatter.numberStyle = .decimal
    formatter.maximumFractionDigits = 0
    data.setValueFormatter(DefaultValueFormatter(formatter: formatter))

    self.pieChartData = data
}

Solution

  • There are two public (to the class) PieChartDataSet init methods.

    The one you're using looks like this: public required init() (which is what causes that default DataSet name to be generated).

    The one you want looks like this: public override init(values: [ChartDataEntry]?, label: String?)

    And you'd pass in an empty string for the label.

    What this means is you'd have to create your PieChartDataEntry array before you call that other PieChartDataSet init(values: insertPieChartDataEntrArrayHere, label: "") function.