Add legend text to pie chart Swift Charts - swift

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.stack.imgur.com/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.

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

Related

LineChart avoid plotting of 0 values

I am using https://github.com/danielgindi/Charts library. I am trying to remove 0 values from the chart but not able to find a particular solution any help would be appreciated.
yAxis has the value of type Double
The chart currently displays:
The updated line chart as I want
var dataEntries: [ChartDataEntry] = []
for i in 0..<forX.count {
let dataEntry = ChartDataEntry(x: Double(i), y: forY[i])
print(dataEntry)
dataEntries.append(dataEntry)
}
let lineChartDataSet = LineChartDataSet(entries: dataEntries, label: "")
let lineChartData = LineChartData(dataSet: lineChartDataSet)
chart.data = lineChartData
Just don't add it to your dataEntries
for i in 0..<forX.count {
if forY[i] != 0 {
let dataEntry = ChartDataEntry(x: Double(i), y: forY[i])
print(dataEntry)
dataEntries.append(dataEntry)
}
}
edit: you can check this https://github.com/aiwiguna/ExampleCharts

How can I draw a line from center to custom angle in pi chart? I am using danielgindi/Charts

I use to show the time periods of a day.
I want use this red line for current time show. And I want to select current time part. Thanks for all answers.
setChart(dataPoints: [String], values: [Double], timeName:String, timeLive:String) {
var dataEntries = [PieChartDataEntry]()
for i in 0..<dataPoints.count {
let dataEntry = PieChartDataEntry(value: values[i], label: dataPoints[i])
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(entries: dataEntries, label: "Unit Sold")
pieChartDataSet.sliceSpace = 3
pieChartDataSet.selectionShift = 15
let pieChartData = PieChartData(dataSet: pieChartDataSet)
let pFormatter = NumberFormatter()
pFormatter.numberStyle = .percent
pFormatter.maximumFractionDigits = 1
pFormatter.multiplier = 1
//pFormatter.percentSymbol = " %"
pieChartData.setValueFormatter(DefaultValueFormatter(formatter: pFormatter))
pieChartData.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 11)!)
pieChartData.setValueTextColor(.white)
pieChartDataSet.drawValuesEnabled = false
self.pieChartView.data = pieChartData
self.pieChartView.setNeedsDisplay()
// self.pieChartView.animate(xAxisDuration: 2.0,easingOption: .easeOutElastic)
let highlight = pieChartView.getHighlightByTouchPoint(CGPoint(x: 50, y: 50))
pieChartView.highlightValue(highlight)
var attrString: NSMutableAttributedString?
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
paragraphStyle.alignment = .center
attrString = NSMutableAttributedString(string: "HKJGH JHGHG ")
attrString?.setAttributes([
NSAttributedString.Key.foregroundColor: NSUIColor.black,
NSAttributedString.Key.font: NSUIFont.systemFont(ofSize: 15.0),
NSAttributedString.Key.paragraphStyle: paragraphStyle
], range: NSMakeRange(0, attrString!.length))
}

How can I add names/title/values (months) to Y axis for my line chart?

I am trying to simple line chart. Chart is coming fine and I want to add values/names for every point of x and y axis.
See the following image, this is is comming , but I want to add/show values in x and y axis.
For example: Check in my example code, I mentioned months and unitSold values.
in X axis I wants to show months names and Y axis and I wants to show some unit sold values.
How can I do or show values in x and y axis?
import UIKit
import Charts
class ViewController: UIViewController {
var dataEntries: [ChartDataEntry] = []
// var chartDataBeanArray = [ChartDataBean]()
let months = ["Jan" , "Feb", "Mar", "Apr", "May", "June", "July", "August", "Sept", "Oct", "Nov", "Dec"]
let unitsSold = [24.0,43.0,56.0,23.0,56.0,68.0,48.0,120.0,41.0,34.0,55.9,12.0,34.0]
#IBOutlet weak var chartViewOutlet: LineChartView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setChart(months, values: unitsSold)
}
func setChart(_ dataPoints: [String], values: [Double]) {
print(values)
print(dataPoints)
chartViewOutlet.noDataText = "No data available!"
for i in 0..<values.count {
print("chart point : \(values[i])")
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let line1 = LineChartDataSet(entries: dataEntries, label: "Units Consumed")
line1.colors = [NSUIColor.blue]
line1.mode = .cubicBezier
line1.cubicIntensity = 0.2
let gradient = getGradientFilling()
line1.fill = Fill.fillWithLinearGradient(gradient, angle: 90.0)
line1.drawFilledEnabled = true
let data = LineChartData()
data.addDataSet(line1)
chartViewOutlet.data = data
chartViewOutlet.setScaleEnabled(false)
chartViewOutlet.animate(xAxisDuration: 1.5)
chartViewOutlet.drawGridBackgroundEnabled = false
chartViewOutlet.xAxis.drawAxisLineEnabled = false
chartViewOutlet.xAxis.drawGridLinesEnabled = false
chartViewOutlet.leftAxis.drawAxisLineEnabled = false
chartViewOutlet.leftAxis.drawGridLinesEnabled = false
chartViewOutlet.rightAxis.drawAxisLineEnabled = false
chartViewOutlet.rightAxis.drawGridLinesEnabled = false
chartViewOutlet.legend.enabled = false
chartViewOutlet.xAxis.enabled = false
chartViewOutlet.leftAxis.enabled = false
chartViewOutlet.rightAxis.enabled = false
chartViewOutlet.xAxis.drawLabelsEnabled = false
}
/// Creating gradient for filling space under the line chart
private func getGradientFilling() -> CGGradient {
// Setting fill gradient color
let coloTop = UIColor(red: 141/255, green: 133/255, blue: 220/255, alpha: 1).cgColor
let colorBottom = UIColor(red: 230/255, green: 155/255, blue: 210/255, alpha: 1).cgColor
// Colors of the gradient
let gradientColors = [coloTop, colorBottom] as CFArray
// Positioning of the gradient
let colorLocations: [CGFloat] = [0.7, 0.0]
// Gradient Object
return CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations)!
}
}
EDIT : After adding following code suggested by #marc
chartViewOutlet.xAxis.enabled = true
chartViewOutlet.leftAxis.enabled = true
this is now showing chart.
Now I wants to show months values in bottom (x axis)...how to show it?
You can find source code here if you want to check it: https://drive.google.com/file/d/1vkPqktZ3mX3q9f75-bihVYeublwc2dXE/view?usp=sharing
Add following code in your project.
func setChart(dataPoints: [String], values: [Double]) {
for i in 0 ..< dataPoints.count {
dataEntries.append(ChartDataEntry(x: Double(i), y: values[i]))
}
let lineChartDataSet = LineChartDataSet(entries: dataEntries, label: "Units Consumed")
lineChartDataSet.axisDependency = .left
lineChartDataSet.setColor(UIColor.black)
lineChartDataSet.setCircleColor(UIColor.black) // our circle will be dark red
lineChartDataSet.lineWidth = 1.0
lineChartDataSet.circleRadius = 3.0 // the radius of the node circle
lineChartDataSet.fillAlpha = 1
lineChartDataSet.fillColor = UIColor.black
lineChartDataSet.highlightColor = UIColor.white
lineChartDataSet.drawCircleHoleEnabled = true
var dataSets = [LineChartDataSet]()
dataSets.append(lineChartDataSet)
let lineChartData = LineChartData(dataSets: dataSets)
chartViewOutlet.data = lineChartData
chartViewOutlet.rightAxis.enabled = false
chartViewOutlet.xAxis.drawGridLinesEnabled = false
chartViewOutlet.xAxis.labelPosition = .bottom
chartViewOutlet.xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints)
chartViewOutlet.legend.enabled = true
}
Output:
This works 100%. Try it.

Pie chart isn't drag-able

I am trying to create a pie chart using iOS Charts, and I know that the default setting for the pie chart is for it to be able to let the user drag the pie chart around and look at it from a different angle.
However, it doesn't seem to work here:
func createChildrenPieChart(sections: [String], percents: [Double]) {
var dataEntries = [ChartDataEntry]()
for i in 0...(sections.count - 1) {
let entry = PieChartDataEntry()
entry.y = percents[i]
entry.label = sections[i]
dataEntries.append(entry)
}
let chartDataSet = PieChartDataSet(values: dataEntries, label: "")
let chartData = PieChartData(dataSet: chartDataSet)
childrenPieChart.data = chartData
var colors: [UIColor] = []
for _ in 0..<sections.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)
}
chartDataSet.colors = colors
}
Any help would be appreciated, and I am using Xcode 9, Swift 4.0
You have to set isUserInteractionEnabled
childrenPieChart.isUserInteractionEnabled = true
I have a functioning pieChart where users can rotate, you can try adding this:
childrenPieChart.rotationEnabled = true
childrenPieChart.highlightPerTapEnabled = true
childrenPieChart.maxAngle = 360.0
childrenPieChart.isUserInteractionEnabled = true
childrenPieChart.rotationAngle = 180.0

Charts3.0 - Can not show all the xAxis label if more than 8 value - Swift

I had create a bar chart which had the 9 categories label for the xAxis:
["Foods", "House Loan", "Insurance", "Petrol", "Saving", "Train", "Others", "Books & Magazine", "Car park"]
But in the charts it just show:
Foods, Insurance, Saving, Others and Car park
Any one know how to solve it?
Here the source code for setting xAxis
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let value = values[i] as Double
let dataEntry = BarChartDataEntry(x: Double(i), y:value)
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Total Amount")
var colors: [UIColor] = []
for _ 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)
}
chartDataSet.colors = colors
chartDataSet.colors = ChartColorTemplates.joyful()
barChartView.chartDescription?.text = ""
barChartView.xAxis.labelPosition = .bottom
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.granularity = 1.0
barChartView.xAxis.decimals = 0
let chartData = BarChartData()
chartData.addDataSet(chartDataSet)
barChartView.data = chartData
barChartView.xAxis.valueFormatter = self
let format = NumberFormatter()
format.numberStyle = .decimal
let formatter = DefaultValueFormatter(formatter: format)
chartData.setValueFormatter(formatter)
barChartView.animate(xAxisDuration: TimeInterval(1))
}
Just need to set the label count.
barChartView.xAxis.labelCount = dataPoints.count