Hell my friends.I'm developing an app which has to show several charts using UIKit and the library Charts. I've been requested to use both things.
I have two arrays with correct data Ciudades y Precios.
Ciudades is String type and Precios Double type. I'v been reading how to use Charts library for hours but it seems that I dont understand how to use it because the chart I get it's not the one I excpected to. I need a chart with the cities on x label but they are not showed as you can see in the picture.
This is my code
class BarChartViewController: UIViewController, ChartViewDelegate {
#IBOutlet weak var barChartView: BarChartView!
var nombres: [String]!
var precios: [Double]!
override func viewDidLoad() {
super.viewDidLoad()
barChartView.delegate = self
nombres = eventos.devolverNombre()
print(nombres)
precios = eventos.devolverPrecios()
setChart(dataPoints: nombres, values: precios)
}
func setChart(dataPoints: [String], values: [Double]) {
barChartView.noDataText = "Es necesario aƱadir datos."
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
if dataEntry != nil {
dataEntries.append(dataEntry)}
}
let chartDataSet = BarChartDataSet(entries: dataEntries, label: "PRECIOS POR EVENTO")
let chartData = BarChartData(dataSet: chartDataSet)
chartDataSet.colors = [UIColor(red: 230/255, green: 126/255, blue: 34/255, alpha: 1)]
chartDataSet.colors = ChartColorTemplates.colorful()
barChartView.data = chartData
barChartView.xAxis.valueFormatter = DefaultAxisValueFormatter(block: {(index, _) in
return self.nombres[Int(index)] })
let labelCount = nombres.count
print(labelCount)
barChartView.xAxis.setLabelCount(labelCount, force: true)
barChartView.xAxis.labelRotationAngle = 90
barChartView.xAxis.centerAxisLabelsEnabled = true
barChartView.xAxis.labelPosition = .bottom
barChartView.xAxis.labelFont = UIFont.systemFont(ofSize: 10)
barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0, easingOption: .easeInBounce)
}
}
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
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.
Problem Statement : Unable to run due to some errors in implementation of Bar-Chart using 'danielgindi/Charts library' in swift 3.0 syntax errors.
Actual Error in Swift 3.0:
After correcting above error, it gives another error in next line, as shown below.
Coding Stuff:
import Charts
class ChartViewController: UIViewController {
#IBOutlet var barChartView: BarChartView!
var months: [String]!
var dataEntries: [BarChartDataEntry] = []
override func viewDidLoad() {
super.viewDidLoad()
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, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]
setChart(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
barChartView.noDataText = "You need to provide data for the chart."
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), yValues: [values[i]])
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
let chartData = BarChartData(xVals: months, dataSet: chartDataSet)
barChartView.data = chartData
}
Please help me, how do I resolve such errors in swift 3.0
I've had this issue as well. It was this line here:
let dataEntry = BarChartDataEntry(x: Double(i), yValues: [values[i]])
You cannot convert dataPoints: [String] to type Double.
My solution was to remove the Double. Then that did not satisfy my data types, so I made them all of type [Int] like so:
func setChart(dataPoints: [Int], values: [Int]) {
self.noDataText = "You need to provide data for the chart."
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: Double(values[i]) )
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
let chartData = BarChartData(dataSet: chartDataSet)
self.data = chartData
You can convert [Int] to Double, so that fixed my issue. I changed the variable months: [String] to
let months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
import UIKit
import Charts
class ViewController: UIViewController, ChartViewDelegate {
#IBOutlet weak var barChartView: BarChartView!
weak var axisFormatDelegate: IAxisValueFormatter?
var months: [String]!
var unitsSold = [Double]()
override func viewDidLoad() {
super.viewDidLoad()
barChartView.delegate = self
axisFormatDelegate = self
months = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
unitsSold = [20.0, 54.0, 6.0, 30.0, 92.0, 16.0,114.0]
setChart(dataPoints: months, values: unitsSold)
}
func setChart(dataPoints: [String], values: [Double]) {
barChartView.noDataText = "You need to provide data for the chart."
// Prevent from setting an empty data set to the chart (crashes)
guard dataPoints.count > 0 else { return }
var dataEntries = [BarChartDataEntry]()
for i in 0..<dataPoints.count {
let entry = BarChartDataEntry(x: Double(i), y: values[i], data: months as AnyObject?)
dataEntries.append(entry)
}
let chartDataSet = BarChartDataSet(entries: dataEntries, label: "Units Sold")
chartDataSet.drawValuesEnabled = false
chartDataSet.colors = [UIColor.red]
chartDataSet.colors = [UIColor.lightGray]
chartDataSet.highlightColor = UIColor.orange.withAlphaComponent(0.3)
chartDataSet.highlightAlpha = 1
let chartData = BarChartData(dataSet: chartDataSet)
barChartView.data = chartData
let xAxisValue = barChartView.xAxis
xAxisValue.valueFormatter = axisFormatDelegate
// chartDataSet.colors = ChartColorTemplates.colorful() //multiple colors
//Animation bars
barChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0, easingOption: .easeInCubic)
// X axis configurations
barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.granularity = 1
barChartView.xAxis.drawAxisLineEnabled = true
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.xAxis.labelFont = UIFont.systemFont(ofSize: 15.0)
barChartView.xAxis.labelTextColor = UIColor.black
barChartView.xAxis.labelPosition = .bottom
// Right axis configurations
barChartView.rightAxis.drawAxisLineEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawLabelsEnabled = false
// Other configurations
barChartView.highlightPerDragEnabled = false
barChartView.chartDescription?.text = ""
barChartView.legend.enabled = false
barChartView.pinchZoomEnabled = false
barChartView.doubleTapToZoomEnabled = false
barChartView.scaleYEnabled = false
barChartView.drawMarkers = true
let l = barChartView.legend
l.horizontalAlignment = .left
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.drawInside = false
l.form = .circle
l.formSize = 9
l.font = UIFont(name: "HelveticaNeue-Light", size: 11)!
l.xEntrySpace = 4
// On tapped bar marker before adding BalloonMarker.swift
let marker = BalloonMarker(color: UIColor.orange, font: UIFont.boldSystemFont(ofSize: 13), textColor: UIColor.white, insets: UIEdgeInsets(top: 7.0, left: 7.0, bottom: 15.0, right: 7.0))
marker.chartView = barChartView
barChartView.marker = marker
}
}
extension ViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return months[Int(value)]
}
}
Install pod file
Assign barchartview class to chart view in storyboad
Follow setchart() method
For ballon marker add BallonMarker.swift file to your project library for this file chartsDemo->Components-> BallonMarker.swift
I have implemented a demo for that
This will Support Swift 4.2 and above
Check this link :
https://github.com/vijay1864/Barchart-Demo-with-Charts-Library
This Demo was Made with help of danielgindi Charts Library
https://github.com/danielgindi/Charts
You can iterate month and units sold values as xVal and yVal.
var barChartValues: [BarChartDataEntry] = []
for (key,val) in self.barChartDataval.enumerated() {
let xVal = Double(key)
let yVal = Double(val.cost)
let dataEntry = BarChartDataEntry(x: xVal, y: yVal!)
barChartValues.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: barChartValues, label: "Expenses Summary")
chartDataSet.colors = [Constants.k_COLORS.BLUE]
var dataSets = [IChartDataSet]()
dataSets.append(chartDataSet)
let chartData = BarChartData(dataSets: dataSets)
self.barChartView.data = chartData
self.barChartView.chartDescription?.text = ""
self.barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInBounce)
For Line chart We can have following
import UIKit
import Charts
class LineChartVC: UIViewController , ChartViewDelegate{
#IBOutlet var lineChartView: LineChartView!
var months: [String]!
override func viewDidLoad() {
super.viewDidLoad()
self.lineChartSetUp()
}
}
extension LineChartVC{
func lineChartSetUp(){
self.lineChartView.delegate = self
self.lineChartView.chartDescription?.enabled = false//true
self.lineChartView.dragEnabled = true
self.lineChartView.setScaleEnabled(true)
self.lineChartView.pinchZoomEnabled = true
self.lineChartView.drawGridBackgroundEnabled = false
// x-axis limit line
/*
let llXAxis = ChartLimitLine(limit: 10.0, label: "Index 10")
llXAxis.lineWidth = 4.0
llXAxis.lineDashLengths = [(10.0), (10.0), (0.0)]
llXAxis.labelPosition = ChartLimitLine.LabelPosition.rightBottom//ChartLimitLabelPositionRightBottom
llXAxis.valueFont = UIFont.systemFont(ofSize: 10.0)
//[_chartView.xAxis addLimitLine:llXAxis];
self.lineChartView.xAxis.gridLineDashLengths = [10.0, 10.0]
self.lineChartView.xAxis.gridLineDashPhase = 0.0
let ll1 = ChartLimitLine(limit: 150.0, label: "Upper Limit")
ll1.lineWidth = 4.0
ll1.lineDashLengths = [5.0, 5.0]
ll1.labelPosition = ChartLimitLine.LabelPosition.rightTop //ChartLimitLabelPositionRightTop
ll1.valueFont = UIFont.systemFont(ofSize: 10.0)
let ll2 = ChartLimitLine(limit: -30.0, label: "Lower Limit")
ll2.lineWidth = 4.0
ll2.lineDashLengths = [5.0, 5.0]
ll2.labelPosition = ChartLimitLine.LabelPosition.rightBottom//ChartLimitLabelPositionRightBottom
ll2.valueFont = UIFont.systemFont(ofSize: 10.0)
let leftAxis: YAxis? = self.lineChartView.leftAxis
leftAxis?.removeAllLimitLines()
// leftAxis?.addLimitLine(ll1)
// leftAxis?.addLimitLine(ll2)
// leftAxis?.axisMaximum = 200.0
// leftAxis?.axisMinimum = -50.0
// leftAxis?.axisMaximum = 100.0
// leftAxis?.axisMinimum = 0.0
//
leftAxis?.gridLineDashLengths = [5.0, 5.0]
leftAxis?.drawZeroLineEnabled = false
leftAxis?.drawLimitLinesBehindDataEnabled = true
self.lineChartView.rightAxis.enabled = false
//[_chartView.viewPortHandler setMaximumScaleY: 2.f];
//[_chartView.viewPortHandler setMaximumScaleX: 2.f];
*/
let marker = BalloonMarker(color: UIColor(white: 180 / 255.0, alpha: 1.0), font: UIFont.systemFont(ofSize: 12.0), textColor: UIColor.white, insets: UIEdgeInsetsMake(8.0, 8.0, 20.0, 8.0))
marker.chartView = self.lineChartView
marker.minimumSize = CGSize(width: 80.0, height: 40.0)
self.lineChartView.marker = marker
self.lineChartView.legend.form = Legend.Form(rawValue: 5)!
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, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]
self.setChart(months, values: unitsSold)
}
func setChart(_ dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x:Double(i) , y: values[i])
dataEntries.append(dataEntry)
}
print(dataEntries )
let data = LineChartData()
let ds1 = LineChartDataSet(values: dataEntries, label: "Units Sold")
ds1.colors = [UIColor.red]
data.addDataSet(ds1)
self.lineChartView.data = data
}
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: Highlight) {
// print("\(entry.value) in \(months[dataSetIndex])")
print(entry )
}
}
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