danielgindi/iOSCharts chartValueSelected not called - ios

I am using danielgindi/iOSCharts library to crate combined line&bar charts like below.
My chart is rendered correctly and it has user interactions like tap and pinch zoom. Also chart is able to detect my tap gesture. But somehow
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: Highlight){
print("###################")
}
cannot be called. Really need some help here.
What I want to implement is that both balloon mark with same X value would show if I click on either a bar or a point on line. (both mark in above two pictures will display at same time when I tap a bar or a point)
Below is my entire controller code:
class FirstViewController: UIViewController,ChartViewDelegate {
#objc(ChartFormatter)
public class ChartFormatter: NSObject, IAxisValueFormatter{
var months: [String]! = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return months[Int(value)]
}
}
#IBOutlet weak var chartView: CombinedChartView!
var lineChartData = LineChartData()
var barChartData = BarChartData()
override func viewDidLoad() {
super.viewDidLoad()
chartView.delegate = self
chartView.chartDescription?.enabled = true
chartView.dragEnabled = true
chartView.setScaleEnabled(true)
chartView.pinchZoomEnabled = true
chartView.drawGridBackgroundEnabled = false
let xAxis:XAxis = chartView.xAxis
xAxis.labelPosition = .bottom
xAxis.labelFont = UIFont.systemFont(ofSize: 11.0)
xAxis.labelTextColor = UIColor.black
xAxis.drawGridLinesEnabled = true
xAxis.drawAxisLineEnabled = false
xAxis.drawLabelsEnabled = false
let leftAxis:YAxis = chartView.leftAxis;
leftAxis.labelTextColor = UIColor(red: 1, green: 165/255, blue: 0, alpha: 1)
leftAxis.axisMaximum = 5.0
leftAxis.axisMinimum = -5.0
leftAxis.drawGridLinesEnabled = false
leftAxis.drawZeroLineEnabled = true
leftAxis.granularityEnabled = true
leftAxis.drawLabelsEnabled = false
let rightAxis:YAxis = chartView.rightAxis
rightAxis.enabled = false
let credit: [Double] = [1.0, 4.0, 2.0, 3.0, 3.0, 1.0, 3.0, 0.0, 0.0, 0.0, 0.0]
let gpa: [Double] = [-1.0, -4.0, -1.5, -1.4, -1.3, -1.0, -3.0, 0.0, 0.0, 0.0, 0.0]
let chartDescription = ""
let marker = BalloonMarker(color: UIColor(white: 180/255, alpha: 1.0), font: UIFont.systemFont(ofSize:12.0), textColor: UIColor.white, insets: UIEdgeInsetsMake(8.0, 8.0, 20.0, 8.0))
marker.chartView = chartView
marker.minimumSize = CGSize(width:80.0, height:40.0)
chartView.marker = marker
self.setLineChart(dataPoints: gpa, chartDescription: chartDescription)
self.setBarChart(dataPoints: credit)
self.setChartData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setLineChart(dataPoints: [Double], chartDescription: String) {
let formatter:ChartFormatter = ChartFormatter()
let xaxis:XAxis = XAxis()
var dataEntries: [ChartDataEntry] = Array()
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i), y: dataPoints[i])
dataEntries.append(dataEntry)
formatter.stringForValue(Double(i), axis: xaxis)
}
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Credit")
self.lineChartData = LineChartData(dataSet: lineChartDataSet)
xaxis.valueFormatter = formatter
chartView.xAxis.valueFormatter = xaxis.valueFormatter
xaxis.drawGridLinesEnabled = false
lineChartDataSet.mode = .linear
lineChartDataSet.drawCirclesEnabled = false
lineChartDataSet.drawValuesEnabled = false
lineChartDataSet.colors = [UIColor.brown]
chartView.descriptionText = chartDescription
}
func setBarChart(dataPoints: [Double]) {
let formatter:ChartFormatter = ChartFormatter()
let xaxis:XAxis = XAxis()
var dataEntries: [BarChartDataEntry] = Array()
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: dataPoints[i])
dataEntries.append(dataEntry)
formatter.stringForValue(Double(i), axis: xaxis)
}
let barChartDataSet = BarChartDataSet(values: dataEntries, label: "GPA")
self.barChartData = BarChartData(dataSet: barChartDataSet)
xaxis.valueFormatter = formatter
chartView.xAxis.valueFormatter = xaxis.valueFormatter
xaxis.drawGridLinesEnabled = false
barChartDataSet.drawValuesEnabled = false
}
func setChartData() {
let data:CombinedChartData = CombinedChartData()
data.lineData = self.lineChartData
data.barData = self.barChartData
chartView.data = data
chartView.data?.highlightEnabled = true
//chartView.autoScaleMinMaxEnabled = true
//chartView.setNeedsDisplay()
}
#objc func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: Highlight){
print("###################")
}
#objc func chartValueNothingSelected(chartView: ChartViewBase){
NSLog("chartValueNothingSelected");
}
}

Chiming in very late here, but the method signature has changed in Swift 3.0 (see this answer), and no longer includes dataSetIndex.
You should be able to see this firing in the console by changing your function signature (and implementation) to the following:
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight){
print("###################")
}

Now it's
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight){
print("Point: \(entry.x) Value: \(entry.y)")
}

Related

iOS Charts(Daniel Gindi) - Two LineChartDataSet with different color failed

I am trying to build a graph with 2 LineChartDataSet. At the first time, I build with one and then on every selected value, I want to do some different color to the right data set yet it seems like the last set sort of run over the settings and do it the opposite:
class GraphTableViewCell: UITableViewCell {
#IBOutlet weak var yieldLabel: UILabel!
#IBOutlet weak var yieldPercentLabel: UILabel!
#IBOutlet weak var lineChart: LineChartView!
#IBOutlet weak var graphButtonView: AssetGraphButtonView!
#IBOutlet weak var endDateLabel: UILabel!
#IBOutlet weak var startDateLabel: UILabel!
var selectionView: AssetGraphSelectionView!
var viewModel: GraphViewModelType!
var set: LineChartDataSet!
var set1: LineChartDataSet!
var marker = BalloonMarker(color: .red,
font: UIFont.systemFont(ofSize: 15),
textColor: .white,
insets: UIEdgeInsets(top: 5, left: 5, bottom: 10, right: 3))
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
override func layoutSubviews() {
super.layoutSubviews()
}
func config(with viewModel: GraphViewModelType) {
self.viewModel = viewModel
yieldLabel.attributedText = viewModel.titleAttributeText
yieldPercentLabel.attributedText = viewModel.yielAttributeText
startDateLabel.attributedText = viewModel.startDateAttributeText
endDateLabel.attributedText = viewModel.endDateAttributeText
graphButtonView.confgiureCell(with: self.viewModel.btnData)
setUpChart()
}
func setUpChart() {
lineChart.delegate = self
lineChart.noDataText = "No Data Available"
lineChart.rightAxis.enabled = false
lineChart.leftAxis.enabled = false
lineChart.xAxis.enabled = false
lineChart.legend.enabled = false
lineChart.xAxis.drawGridLinesEnabled = false
lineChart.drawMarkers = true
lineChart.doubleTapToZoomEnabled = false
lineChart.pinchZoomEnabled = false
lineChart.scaleXEnabled = false
lineChart.scaleYEnabled = false
marker.chartView = lineChart
marker.minimumSize = CGSize(width: 28, height: 20)
lineChart.marker = marker
let dataSets = viewModel.getLineChartDataSet()
let data = LineChartData(dataSets: dataSets)
data.setValueFont(.systemFont(ofSize: 7, weight: .light))
lineChart.data = data
}
extension GraphTableViewCell: ChartViewDelegate {
func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
let transform = lineChart.getTransformer(forAxis: .left)
let point = transform.pixelForValues(x: highlight.x, y: highlight.y)
print("point : x = \(point.x) y = \(point.y)")
let color = self.lineChart.colorOfPoint(point: point)
marker.color = color
let dataSets = viewModel.chartValueSelected(entry: entry)
lineChart.data = dataSets
}
}
This is the viewModel:
final class GraphTableViewCellViewModel: GraphViewModelType {
var startDateAttributeText = NSMutableAttributedString()
var endDateAttributeText = NSMutableAttributedString()
var titleAttributeText = NSMutableAttributedString(string: "", attributes: [NSAttributedString.Key.font : UIFont(name: "Orion-Bold", size: 14)!, NSAttributedString.Key.foregroundColor : UIColor.black])
var yielAttributeText = NSMutableAttributedString(string: "\(String(format: "%.2f%%", abs(14)))", attributes: [NSAttributedString.Key.font : UIFont(name: "Orion-Bold", size: 14)!, NSAttributedString.Key.foregroundColor : UIColor.green])
let disposeBag = DisposeBag()
var btnData: [AssetGraphButtonViewViewModel]
var data: TwrGraph
var dataSet = [LineChartDataSet]()
var set: LineChartDataSet!
var set1: LineChartDataSet!
init(with data: TwrGraph) {
btnData = AssetGraphViewModel(security: nil).assetGraphData
self.data = data
startDateAttributeText = NSMutableAttributedString(string: data.startDate, attributes: [NSAttributedString.Key.font : UIFont(name: "Orion-Regular", size: 12)!, NSAttributedString.Key.foregroundColor : ColorName.warmGreyTwo])
endDateAttributeText = NSMutableAttributedString(string: data.endDate, attributes: [NSAttributedString.Key.font : UIFont(name: "Orion-Regular", size: 12)!, NSAttributedString.Key.foregroundColor : ColorName.warmGreyTwo])
}
func getChartDataPoints(dataPoints: [String], values: [Double]) -> [ChartDataEntry] {
var dataEntries: [ChartDataEntry] = []
for count in (0..<dataPoints.count) {
dataEntries.append(ChartDataEntry.init(x: Double(count), y: values[count]))
}
return dataEntries
}
func getLineChartDataSet() -> [LineChartDataSet] {
let dataWeeklyDate = self.data.weeklyGraph.map { $0.date }
let dataWeeklyYield = self.data.weeklyGraph.map { $0.yield }
let dataPoints = getChartDataPoints(dataPoints: dataWeeklyDate, values: dataWeeklyYield)
set = LineChartDataSet(entries: dataPoints, label:"")
setup(set)
return [set]
}
func setup(_ dataSet: LineChartDataSet) {
dataSet.drawHorizontalHighlightIndicatorEnabled = false
dataSet.drawVerticalHighlightIndicatorEnabled = true
dataSet.isDrawLineWithGradientEnabled = true
dataSet.fillAlpha = 0.15
dataSet.lineWidth = 2
dataSet.circleRadius = 0
dataSet.drawCircleHoleEnabled = false
dataSet.drawCirclesEnabled = false
dataSet.drawValuesEnabled = false
dataSet.highlightColor = .blue
let rightColor = [ChartColorTemplates.colorFromString("#FA3A7A"), ChartColorTemplates.colorFromString("#C257B1"),
ChartColorTemplates.colorFromString("#8B73E8")]
dataSet.colors = rightColor
dataSet.gradientPositions = [0, 40, 100]
let gradientColors = [ChartColorTemplates.colorFromString("#FC4684").cgColor,
ChartColorTemplates.colorFromString("#D8D8D8").cgColor]
let colorLocations:[CGFloat] = [1.0, 0.0]
if let gradient = CGGradient(colorsSpace: nil, colors: gradientColors as CFArray, locations: colorLocations) {
dataSet.fill = LinearGradientFill(gradient: gradient, angle: 90.0)
}
dataSet.drawFilledEnabled = true
}
func updateSetAfterTouch(_ dataSet: LineChartDataSet) {
dataSet.drawHorizontalHighlightIndicatorEnabled = false
dataSet.drawVerticalHighlightIndicatorEnabled = true
// dataSet.isDrawLineWithGradientEnabled = true
dataSet.fillAlpha = 0.15
dataSet.lineWidth = 2
dataSet.circleRadius = 0
dataSet.drawCircleHoleEnabled = false
dataSet.drawCirclesEnabled = false
dataSet.drawValuesEnabled = false
// dataSet.highlightColor = .blue
dataSet.colors = [.red]
}
func chartValueSelected(entry: ChartDataEntry) -> LineChartData {
return updateSet(with: entry)
}
func updateSet(with entry: ChartDataEntry) -> LineChartData {
var dataEntries: [ChartDataEntry] = []
var dataEntries1: [ChartDataEntry] = []
for count in (0..<self.data.weeklyGraph.count) {
if count < self.data.weeklyGraph.count && count < Int(entry.x) {
dataEntries.append(ChartDataEntry.init(x: Double(count), y: self.data.weeklyGraph[count].yield))
} else {
dataEntries1.append(ChartDataEntry.init(x: Double(count), y: self.data.weeklyGraph[count].yield))
}
}
set = LineChartDataSet(entries: dataEntries, label:"")
set1 = LineChartDataSet(entries: dataEntries1, label:"")
setup(set)
updateSetAfterTouch(set1)
let data = LineChartData(dataSets: [set1, set])
return data
}
}
As you can see when value is selected and I am using it to create two ChartDataEntry and the two LineChartDataSet that one continue the other (in the x axis ). This is the image when we first entering(looks fine):
This is the image when selecting:
After creating two LineChartDataSet add a different colour for each set.
func updateGraph(){
//create 2 ChartDataEntry arrays for both sets
var dataEntries : [ChartDataEntry] = []
var dataEntries1 : [ChartDataEntry] = []
//use ur condition here to devide the data in to two groups
for i in 0..<numbers.count {
if i < 3{
let value = ChartDataEntry(x: Double(i), y: numbers[i]) // here we set the X and Y status in a data chart entry
dataEntries.append(value)
}else{
let value = ChartDataEntry(x: Double(i), y: numbers[i]) // here we set the X and Y status in a data chart entry
dataEntries1.append(value)
}
}
//I add the last element of the first array to the begining of the first array to stop discontinue
dataEntries1.insert(dataEntries.last!, at: 0)
//create data set 1
let set1 = LineChartDataSet(entries: dataEntries, label: "Number")
set1.colors = [UIColor.blue]
//create data set 2
let set2 = LineChartDataSet(entries: dataEntries1, label: "Number")
set2.colors = [UIColor.red]
//This is the object that will be added to the chart
let data = LineChartData(dataSets: [set1, set2])
chtChart.data = data //finally - it adds the chart data to the chart and causes an update
}
My Output looks like follows.
Full ViewController Code
class ViewController: UIViewController {
#IBOutlet weak var txtTextBox: UITextField!
#IBOutlet weak var chtChart: LineChartView!
var numbers : [Double] = [] //This is where we are going to store all the numbers. This can be a set of numbers that come from a Realm database, Core data, External API's or where ever else
override func viewDidLoad() {
super.viewDidLoad()
var dataEntries : [ChartDataEntry] = []
numbers = [2,4,7,3,4,5,8,9,1,2,9]
for i in 0..<numbers.count{
let value = ChartDataEntry(x: Double(i), y: numbers[i]) // here we set the X and Y status in a data chart entry
dataEntries.append(value)
}
let dataSet = LineChartDataSet(entries: dataEntries, label: "Number")
dataSet.drawHorizontalHighlightIndicatorEnabled = false
dataSet.drawVerticalHighlightIndicatorEnabled = true
dataSet.drawHorizontalHighlightIndicatorEnabled = true
dataSet.fillAlpha = 0.15
dataSet.lineWidth = 2
dataSet.circleRadius = 0
dataSet.drawCircleHoleEnabled = false
dataSet.drawCirclesEnabled = false
dataSet.drawValuesEnabled = false
dataSet.highlightColor = .blue
dataSet.colors = [UIColor.green]
let data = LineChartData(dataSets: [dataSet])
chtChart.data = data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func btnbutton(_ sender: Any) {
// let input = Double(txtTextBox.text!) //gets input from the textbox - expects input as double/int
// numbers.append(input!) //here we add the data to the array.
updateGraph()
txtTextBox.text = ""
}
func updateGraph(){
//create 2 ChartDataEntry arrays for both sets
var dataEntries : [ChartDataEntry] = []
var dataEntries1 : [ChartDataEntry] = []
//use ur condition here to devide the data in to two groups
for i in 0..<numbers.count {
if i < 3{
let value = ChartDataEntry(x: Double(i), y: numbers[i]) // here we set the X and Y status in a data chart entry
dataEntries.append(value)
}else{
let value = ChartDataEntry(x: Double(i), y: numbers[i]) // here we set the X and Y status in a data chart entry
dataEntries1.append(value)
}
}
//I add the last element of the first array to the begining of the first array to stop discontinue
dataEntries1.insert(dataEntries.last!, at: 0)
//create data set 1
let set1 = LineChartDataSet(entries: dataEntries, label: "Number")
set1.colors = [UIColor.blue]
set1.drawHorizontalHighlightIndicatorEnabled = false
set1.drawVerticalHighlightIndicatorEnabled = true
set1.drawHorizontalHighlightIndicatorEnabled = true
set1.fillAlpha = 0.15
set1.lineWidth = 2
set1.circleRadius = 0
set1.drawCircleHoleEnabled = false
set1.drawCirclesEnabled = false
set1.drawValuesEnabled = false
set1.highlightColor = .blue
//create data set 2
let set2 = LineChartDataSet(entries: dataEntries1, label: "Number")
set2.colors = [UIColor.red]
set2.drawHorizontalHighlightIndicatorEnabled = false
set2.drawVerticalHighlightIndicatorEnabled = true
set2.drawHorizontalHighlightIndicatorEnabled = true
set2.fillAlpha = 0.15
set2.lineWidth = 2
set2.circleRadius = 0
set2.drawCircleHoleEnabled = false
set2.drawCirclesEnabled = false
set2.drawValuesEnabled = false
set2.highlightColor = .blue
//This is the object that will be added to the chart
let data = LineChartData(dataSets: [set1, set2])
chtChart.data = data //finally - it adds the chart data to the chart and causes an update
}
}

Don't show month in Chart in swift3

I want to display the chart in Swift 3 but why the month name is not showing, is there anyone with coding?
#IBOutlet var utilizationChart: LineChartView!
override func viewDidLoad() {
super.viewDidLoad()
let months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 18.0, 19.0, 21.0, 24.0, 30.0, 16.0]
setChart(dataPoints: months, values: unitsSold)
utilizationChart.chartDescription?.text = ""
utilizationChart.backgroundColor = UIColor.clear
utilizationChart.noDataText = "No chart data available"
}
func setChart(dataPoints: [String], values: [Double]) {
utilizationChart.delegate = self
var dataEntries: [ChartDataEntry] = []
for i in 0..<values.count {
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Utilization")
let lineChartData = LineChartData(dataSet: lineChartDataSet)
utilizationChart.data = lineChartData
}

iOS Charts show only one chart segment

I try to setup a pie chart from Charts library with two items. My code if following
lazy var pieChart : PieChartView = {
let pie = PieChartView()
pie.data?.setValueTextColor(UIColor.abClear())
pie.chartDescription?.enabled = false
pie.legend.enabled = false
return pie
}()
override func viewDidLoad() {
super.viewDidLoad()
let months = ["Jan", "Feb"]
let unitsSold = [10.0, 10.0]
setChart(dataPoints: months, values: unitsSold)
}
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)
}
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "")
pieChartDataSet.drawValuesEnabled = false
let pieChartData = PieChartData(dataSet: pieChartDataSet)
pieChart.data = pieChartData
pieChartDataSet.colors = [UIColor.red, UIColor.blue]
}
The problem is that chart draws only one item - blue one. Looks like this
What am I doing wrong ?
I checked your code. The problem is the values you are setting for x and y in ChartDataEntry. Change your code in the function setChart(dataPoints: [String], values: [Double]):
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])//ChartDataEntry(x: values[i], y: Double(i))
dataEntries.append(dataEntry)
}

How do I display labels on bottom axis (xVals) correctly on iOS Chart?

I have been following very simple tutorial of iOS Charts.
The values in my chart are now showing correctly, however the label on the bottom is not showing.
override func viewDidLoad() {
results = ["Won", "Drawn", "Lost"]
let games = [totalWins, totalDraws, totalLosses]
setChart(dataPoints: results, values: games)
}
// CHART FUNCTION ************
func setChart(dataPoints: [String], values: [Double]){
barChartView.noDataText = "you need to provide some data for the chart."
var dataEntries: [BarChartDataEntry] = Array()
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Games Played")
//let chartData = BarChartData(xVals: self.results, dataSet: dataEntries)
let chartData = BarChartData()
self.barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
barChartView.leftAxis.granularityEnabled = true
barChartView.rightAxis.enabled = false
barChartView.leftAxis.granularity = 1.0
chartData.addDataSet(chartDataSet)
barChartView.data = chartData
}
// END OF CHART FUNCTION ***********
As you can see it is displaying numbers, rather than "Won, Drawn, Lost"
I believe this is because I need to assign the labels in a command like this:
let chartData = BarChartData(xVals: self.results, dataSet: dataSet)
chartView.data = chartData
But I get errors and I don't know what needs to go in dataSet as I took that solution from another thread and can't seem to amend it to work.
Temp image:
You have interchanges x and y values.
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
And to get the X-Axis at the bottom, you have to add the following.
self.barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
Please find my working code for a sample dataset.
class BarChartViewController: UIViewController {
#IBOutlet weak var barChartView: BarChartView!
override func viewDidLoad() {
super.viewDidLoad()
let values = [11.00, 90.95, 250.00, 40.90, 60.88, 99.99, 25.00]
setChart(values: values)
}
func setChart(values: [Double]) {
var daysEntries: [BarChartDataEntry] = []
for i in 0..<values.count {
let dataEntry = BarChartDataEntry(x : Double(i), y : values[i])
daysEntries.append(dataEntry)
}
let data = BarChartData()
let ds1 = BarChartDataSet(values: daysEntries, label: "Days")
ds1.colors = [NSUIColor.red]
data.addDataSet(ds1)
self.barChartView.data = data
self.barChartView.gridBackgroundColor = NSUIColor.white
self.barChartView.chartDescription?.text = "Barchart Days and Gross"
self.barChartView.rightAxis.enabled = true
self.barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
self.barChartView.xAxis.axisRange = 5.0
}
override func viewWillAppear(_ animated: Bool) {
self.barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
}
}
Thanks
Sriram
I had the same issue and I fixed it with these three lines :
self.xAxis.granularity = 1
self.xAxis.granularityEnabled = true
self.xAxis.labelCount = // number of points on X axis
// xAxis.labelFont = UIFont.systemFont(ofSize: 13.0)
// xAxis.labelTextColor = .lightGray
xAxis.labelPosition = .bottom
xAxis.setLabelCount(dataPoints.count, force: false)
if xAxis.labelPosition == .bottom {
xAxis.valueFormatter = IndexAxisValueFormatter(values: dataPoints)
}
xAxis.granularity = 1.0
I hope this would help you with controlling the xAxis label positions.
First method
chartView.setExtraOffsets(left: 20, top: 0, right: 0, bottom: 0)
Second method
chartView.xAxis.avoidFirstLastClippingEnabled = true

Pie chart using Charts library with swift

I am integrating pie chart in my app using Charts library and getting issue with chart data my code is
import UIKit
import Charts
class ViewController: UIViewController {
#IBOutlet weak var pieChartView: PieChartView!
override func viewDidLoad() {
super.viewDidLoad()
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let unitsSold = [10.0, 4.0, 6.0, 3.0, 12.0, 16.0]
setChart(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry1 = ChartDataEntry(x: Double(i), y: values[i], data: dataPoints[i] as AnyObject)
dataEntries.append(dataEntry1)
}
print(dataEntries[0].data)
let pieChartDataSet = PieChartDataSet(values: dataEntries, label: "Units Sold")
let pieChartData = PieChartData(dataSet: pieChartDataSet)
pieChartView.data = pieChartData
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
}
}
and when run app I getting something this
but I need pie chart in full data records like in below screen shot
Update for this question.
func updateChartData() {
let chart = PieChartView(frame: self.view.frame)
// 2. generate chart data entries
let track = ["Income", "Expense", "Wallet", "Bank"]
let money = [650, 456.13, 78.67, 856.52]
var entries = [PieChartDataEntry]()
for (index, value) in money.enumerated() {
let entry = PieChartDataEntry()
entry.y = 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)
chart.data = data
chart.noDataText = "No data available"
// user interaction
chart.isUserInteractionEnabled = true
let d = Description()
d.text = "iOSCharts.io"
chart.chartDescription = d
chart.centerText = "Pie Chart"
chart.holeRadiusPercent = 0.2
chart.transparentCircleColor = UIColor.clear
self.view.addSubview(chart)
}
The reason all the information isn't showing up is because you are using a parent initialiser when creating the entry point.
Instead of
let dataEntry1 = ChartDataEntry(x: Double(i), y: values[i], data: dataPoints[i] as AnyObject)
try this instead
let dataEntry1 = PieChartDataEntry(value: Double(i), label: dataPoints[i], data: dataPoints[i] as AnyObject)
The PieChartDataEntry is specifically for Pie charts so you should see the month show up in the chart.
Hopefully this gets you on the right track

Resources