ios-charts PieChart's label (legends) missing - ios

I am trying to implement pie chart from ios-charts library everything is working great, however I am missing legends from the graph -
Here is my code -
// This is the delegate method for creating data for chart
func offDaysDidLoaded(controller: DataModel,chartArray:[PFObject]) {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM"
dataDict = [:]
for od in chartArray {
let date = od["Date"] as! NSDate
let month = formatter.stringFromDate(date)
if self.dateDict.indexForKey(month) != nil {
self.dateDict[month]! += 1.0
}else{
self.dateDict.updateValue(1.0, forKey: month)
}
}
let dataPointArray = Array(dateDict.keys)
let valuesArray = Array(dateDict.values)
pieChartView.data = nil
pieChartView.backgroundColor = UIColor.grayColor()
setChart(dataPointArray, values: valuesArray)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
let pieChartDataSet = PieChartDataSet(yVals: dataEntries, label: "Months")
let pieChartData = PieChartData(xVals: dataPoints, dataSet: pieChartDataSet)
pieChartData.setDrawValues(false)
pieChartView.data = pieChartData
pieChartView.animate(xAxisDuration: NSTimeInterval(5))
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)
}
pieChartDataSet.colors = colors
}
I have seen similar issue in here and build and run, pie chart used in the issue also doesn't show any legends below the chart. Any help or pointer would be really appreciated.
Thanks

Finally this issue is resolved it wasn't the bug. Please find the detailed solution here.

I just did try ChatsDemo with
legend.position = ChartLegendPositionBelowChartLeft;
works fine. So either your data problem, or you modified something. You don't show how you setup x values. Give more details or debug on your own. Should be easy

Related

Ios Swift PieChart

How can I display the legend values in ios pie chart? I was able to get only the non zero values. Can anyone help?
func updateChartData12() {
let chart = PieChartView(frame: self.view.frame)
// 2. generate chart data entries
let track = ["Income", "Expense", "Wallet", "Bank"]
let money = [650, 456.13, 0, 0]
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
let entry = PieChartDataEntry()
if value != 0 {
entry.y = value
entry.label = track[index]
entries.append( entry)
}
}
// 3. chart setup
let set = PieChartDataSet( values: entries, label: "")
// this is custom extension method. Download the code for more details.
var colors: [UIColor] = []
for _ in 0..<money.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)
}
set.colors = colors
let data = PieChartData(dataSet: set)
chart.data = data
chart.noDataText = "No data available"
// user interaction
let d = Description()
chart.chartDescription = d
chart.centerText = "Pie Chart"
chart.holeRadiusPercent = 0.2
chart.transparentCircleColor = UIColor.clear
self.view.addSubview(chart)
}
I am using this code..But I need to display total y values i.e legend at the bottom
Your pie chart is greater than 100%. The data I have is intended to show a total that is over 100% and That the reason it's not work.
let track = ["Income", "Expense", "Wallet", "Bank"]
let money = [650, 456.13, 0, 0]
So use following money array if it's work fine then you would like to check is there build in method to ensure the sum of percentages in the pie chart is 100%
let money = [65, 35, 0, 0]

ERROR - Cannot invoke initializer for type 'LineChartData' with an argument list of type '(xVals: [String], dataSet: LineChartDataSet)'

I am currently using the Charts framework to use a line graph within my app. I have used the code below but an error is occurring. Here is the code-
`func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: values[i], y: Double(i))
dataEntries.append(dataEntry)
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)
}
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold")
let lineChartDataa = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
Graph.data = lineChartDataa
}
`
The error that is occurring is below-
Cannot invoke initializer for type 'LineChartData' with an argument list of type '(xVals: [String], dataSet: LineChartDataSet)'
Any ideas how I could fix this.
You have to use like this :
This is to set LineChartData:
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold")
let lineChartDataa = LineChartData(dataSet: lineChartDataSet)
For setting xAxis labels :
Graph.xAxis.labelPosition = XAxis.LabelPosition.bottom
Graph.xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints)
LineChartData has declared this as init.
public override init(dataSets: [IChartDataSet]?)
Its superclass, ChartData has declared these inits:
#objc public init(dataSets: [IChartDataSet]?)
#objc public convenience init(dataSet: IChartDataSet?)
It looks like the init with params that you are trying, is not available, hence the compiler error.

Using 3rd party "charts",the response values as double.How it make to integer format?

Using third party "charts".the input format of values are Double and response also in double.For example, my input is a=12,b=13,c=20,d=25 when it comes in graph showing like a=12.0,b=13.0,c=20.0,d=25.0
here is my code
func updateChartData() {
let skipped = 12
let correct = 13
let wrong = 20
let timedOut = 25
let track = ["Skipped", "Right", "Wrong", "Not Attended"]
let money = [skipped, correct, wrong, timedOut]
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
let entry = PieChartDataEntry()
entry.y = Double(value)
entry.label = track[index]
entries.append( entry)
}
// 3. chart setup
let set = PieChartDataSet( values: entries, label: "Pie Chart")
// this is custom extension method. Download the code for more details.
var colors: [UIColor] = []
for _ in 0..<money.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)
}
set.colors = colors
let data = PieChartData(dataSet: set)
viewPieCharts.data = data
viewPieCharts.noDataText = "No data available"
// user interaction
viewPieCharts.isUserInteractionEnabled = true
let d = Description()
d.text = "iOSCharts.io"
viewPieCharts.chartDescription = d
viewPieCharts.centerText = "Pie Chart"
viewPieCharts.holeRadiusPercent = 0.5
viewPieCharts.transparentCircleColor = UIColor.clear
}
I want the values without decimal point.
Just insert this code
let format = NumberFormatter()
format.numberStyle = .none
let formatter = DefaultValueFormatter(formatter: format)
data.setValueFormatter(formatter)
after
let data = PieChartData(dataSet: set)
Override IValueFormatter and set it to your PieChartData instance
class MyValueFormatter : IValueFormatter {
func stringForValue(_ value: Double,
entry: ChartDataEntry,
dataSetIndex: Int,
viewPortHandler: ViewPortHandler?) -> String {
return String(format: "%.0f", value)
}
}
data.setValueFormatter(MyValueFormatter())

How to display second y-axis to right of grouped bar chart data in iOS

I am developing one activity tracker iOS application in which I need to show a history of steps and calories in a bar chart. I used iOS Charts
for this. I am able to get the grouped charts by using this but i am not able to show two seperate axis bars for steps and calories. Below is my requirment. Please suggest me how can i achive this using iOS-Charts or suggest me any other charts written in Swift.
Grouped Bar Chart
I wrote the code using iOS Charts library as below,
func setUpDataForCharts()
{
var weekDays = [String]()
for i in 1 ... 7
{
let value = String(i)
weekDays.append(value)
}
let steps = [2000, 4000, 3500, 1300, 5000, 4800, 2400]
let calories = [20.5, 40.3, 34.0, 13.3, 50.0, 80.2, 20.0]
setChartBarGroupDataSet(weekDays, values: steps, values2: calories)
//setChart(weekDays, values: steps)
barChartView.xAxis.labelPosition = ChartXAxis.LabelPosition.Bottom
barChartView.xAxis.drawGridLinesEnabled = false
}
func setChartBarGroupDataSet(dataPoints: [String], values: [Double], values2: [Double]) {
var dataEntries: [BarChartDataEntry] = []
var dataEntries2: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
dataEntries.append(dataEntry)
}
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(value: values2[i], xIndex: i)
dataEntries2.append(dataEntry)
}
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: "Steps")
let chartDataSet2 = BarChartDataSet(yVals: dataEntries2, label: "Calories")
chartDataSet2.colors = [UIColor(hex: "3F7FD0")]
chartDataSet.colors = [UIColor(hex: "F53609")]
let dataSets: [BarChartDataSet] = [chartDataSet,chartDataSet2]
let data = BarChartData(xVals: dataPoints, dataSets: dataSets)
barChartView.data = data
barChartView.descriptionText = ""
barChartView.rightAxis.axisMaxValue = chartDataSet2.yMax + 1.0
barChartView.rightAxis.labelCount = chartDataSet2.valueCount
barChartView.rightAxis.drawGridLinesEnabled = true
barChartView.rightAxis.drawAxisLineEnabled = false
barChartView.rightAxis.drawLabelsEnabled = true
barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .Linear)
}
Out put with the above code is,
Output
Thanks in advance!

Multiple colours to Bar Charts Swift one above the other

I am using CHARTS library in swift.
https://github.com/danielgindi/Charts
I got suceess in creating Pie chart and bar chart.
Now I want to create bar chart with one "x" value and 2 "y" values.
I created the bar chart with two different values.
But I am not able to set the colours for them
I passed the colour array to delegate method setColors but it takes the last colour from the array.
Can any one please guide me for having different colours on bar chart.
Here is my code to call BarChart library
months = ["HR","Operations","iOS","Android","PHP","Support","Testing","Designer"]
let unitsSold = [10.0,20.0,30.0,20.0,20.0,10.0,15.0,20.0]
let unitsSold1 = [20.0,30.0,50.0,40.0,30.0,20.0,45.0,50.0]
let barChartClass = self.storyboard!.instantiateViewControllerWithIdentifier("BarChartViewControllerID") as! BarChartViewController
self.addChildViewController(barChartClass)
barChartClass.view.frame = CGRectMake(20, 20, 740, 900)
barChartClass.barChartView.doubleTapToZoomEnabled = false
barChartClass.barChartView.setScaleEnabled(false)
self.view.addSubview(barChartClass.view)
barChartClass.barChartView.legend.enabled = false
barChartClass.setChartBarGroupDataSet(months, values: unitsSold, values2: unitsSold1, sortIndex: 0)
And this is the method call for setChartBarGroupDataSet
func setChartBarGroupDataSet(dataPoints: [String], values: [Double], values2: [Double],sortIndex:Int)
{
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count
{
let dataEntry = BarChartDataEntry(value: values[i], xIndex: i)
let dataEntry1 = BarChartDataEntry(value: values2[i], xIndex: i)
dataEntries.append(dataEntry)
dataEntries.append(dataEntry1)
}
let chartDataSet = BarChartDataSet(yVals: dataEntries, label: " ")
let COLOR_SET : [UIColor]!
COLOR_SET = [UIColor.redColor(),UIColor.greenColor()]
chartDataSet.setColors(COLOR_SET, alpha: 1.0)
let dataSets: [BarChartDataSet] = [chartDataSet]
let data = BarChartData(xVals: dataPoints, dataSets: dataSets)
barChartView.data = data
barChartView.descriptionText = ""
barChartView.rightAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawAxisLineEnabled = false
barChartView.rightAxis.drawLabelsEnabled = false
barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .EaseInBounce)
}
What I want is something like this
Thanks in advance.
This is a stacked bar chart. In Charts' demos, you can see a stacked bar chart.
Basically, each BarChartDataEntry received either one value, or an array of values. Pass in an array of values - and you are good to go!
let entry = BarChartDataEntry(values: [4.6, 3.8], xIndex: 0)
dataset.colors = [UIColor.cyanColor(), UIColor.greenColor()]
dataset.stackLabels = ["Inactive inventory", "Active inventory"]
Answered in the duplicate issue too: https://github.com/danielgindi/Charts/issues/1324

Resources