iOS Charts -> Last value doesn't appear - ios

I have some troubles with the library, when I create a barChart I have to add an extra value to my values array in order to show all my original values, and in the lineChart the last value appears in the line graph but it doesn't have its value above the point like the others.
I let you my code and some pictures showing the problem:
BarChart: My xAxis have a custom format showing months.
override func viewDidLoad() {
super.viewDidLoad()
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]
max = unitsSold.maxElement()
setChart(unitsSold)
}
func setChart(values: [Double]) {
let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()
barChartView.noDataText = "You need to provide data for the chart."
var dataEntries: [BarChartDataEntry] = []
for i in 0..<values.count {
let dataEntry = BarChartDataEntry(x: Double(i), y:values[i])
dataEntries.append(dataEntry)
formato.stringForValue(Double(i), axis: xaxis)
}
xaxis.valueFormatter = formato
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
chartDataSet.colors = ChartColorTemplates.joyful()
barChartView.fitBars = true //Para que las barras inicial y final se muestren completas
barChartView.xAxis.valueFormatter = xaxis.valueFormatter
barChartView.xAxis.labelPosition = .Bottom
barChartView.leftAxis.axisMinimum = 0
barChartView.leftAxis.axisMaximum = max + 2
barChartView.rightAxis.enabled = false
barChartView.drawValueAboveBarEnabled = false
barChartView.descriptionText = ""
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
let chartData = BarChartData()
chartData.addDataSet(chartDataSet)
barChartView.data = chartData
}
LineChart: My xAxis have a custom format showing months.
override func viewDidLoad() {
super.viewDidLoad()
let unitsSold = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0]
max = unitsSold.maxElement()
setChart(unitsSold)
}
func setChart(values: [Double]) {
let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()
var dataEntries: [ChartDataEntry] = []
for i in 0..<values.count {
let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
formato.stringForValue(Double(i), axis: xaxis)
}
xaxis.valueFormatter = formato
let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold")
lineChartDataSet.colors = ChartColorTemplates.joyful()
lineChartDataSet.circleColors = ChartColorTemplates.joyful()
lineChartDataSet.drawCircleHoleEnabled = false
let lineChartData = LineChartData( dataSet: lineChartDataSet)
lineChartData.setValueFont(UIFont(name: "HelveticaNeue-Light", size: 7))
lineChartView.fitScreen()
lineChartView.xAxis.labelPosition = .Bottom
lineChartView.xAxis.axisMaximum = Double(values.count)
lineChartView.leftAxis.axisMinimum = 0
lineChartView.leftAxis.axisMaximum = max + 3
lineChartView.rightAxis.enabled = false
lineChartView.descriptionText = ""
lineChartView.xAxis.drawGridLinesEnabled = false
lineChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
lineChartView.xAxis.valueFormatter = xaxis.valueFormatter
lineChartView.data = lineChartData
}
The responses are: For barChart December doesn't appear and in lineChart the last value doesn't show its value above it, I hope someone can help.

Related

Not to start xAxis at zero in LineChart iOS Swift

I have created lineChartView. Below xAxis values are displayed hours with 1 hour time interval. My graph starts at 0 and I am not able to show proper xAxis label value.
I want to put extra space in xAxis starting so that the xAxis label can proper visible.
Here is my code:
func setChart(yValues: [Double], xValues: [String]) {
chartView.noDataText = "You need to provide data for the chart."
var dataEntries: [ChartDataEntry] = []
for i in 0..<yValues.count {
let dataEntry = ChartDataEntry(x: Double(i), y: yValues[i])
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(entries: dataEntries, label: "")
chartDataSet.colors = [.black]
chartDataSet.drawFilledEnabled = true
let chartData = LineChartData(dataSet: chartDataSet)
let chartFormatter = LineChartFormatter(labels: xValues)
chartView.xAxis.valueFormatter = chartFormatter
chartView.xAxis.labelCount = dataEntries.count
chartView.data = chartData
chartView.xAxis.granularity = 1.0
chartView.xAxis.granularityEnabled = true
chartView.xAxis.centerAxisLabelsEnabled = false
chartView.xAxis.axisMinimum = 0
chartView.xAxis.axisMaximum = Double(dataEntries.count)
chartView.setVisibleXRange(minXRange: 1.0, maxXRange: 3.0)
}

How to add values to this iOS Bar Chart in White and 14px using Swift?

I have a bar chart which currently looks like this:
I would like to put the value of each bar at the end of the bar in white.
This is my current code:
viewDidLoad{
self.results = ["Lost", "Drawn", "Won"]
let games = [total_Losses, total_Draws, total_Wins]
self.setChart(dataPoints: self.results, values: games)
}
func setChart(dataPoints: [String], values: [Double]){
let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()
let xAxis : XAxis = self.barChartView.xAxis;
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)
formato.stringForValue (Double(i), axis: xaxis)
}
xaxis.valueFormatter = formato
barChartView.xAxis.valueFormatter = xaxis.valueFormatter
xAxis.labelFont = UIFont(name: "Avenir", size: 14.0)!
xAxis.labelTextColor = UIColor.white
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Games Played")
let chartData = BarChartData(dataSets: [chartDataSet])
chartDataSet.colors = ChartColorTemplates.material()
barChartView.leftAxis.enabled = true
barChartView.legend.enabled = false
barChartView.chartDescription?.text = ""
chartData.addDataSet(chartDataSet)
barChartView.data = chartData
barChartView.leftAxis.forceLabelsEnabled = true
barChartView.rightAxis.forceLabelsEnabled = true
barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.granularity = 1.0
barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.rightAxis.enabled = false
barChartView.drawGridBackgroundEnabled = false
self.barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
}
How do I add values to the bars in this chart, in white and pixel size 14?
The answers so far have failed to work - I think the problem may lie within:
for i in 0..<dataPoints.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: values[i])
dataEntries.append(dataEntry)
formato.stringForValue (Double(i), axis: xaxis) // This line has a warning: "Result of call to 'stringForValue(_:axis:)' is unused
}
This above snippet of code calls this class below:
public class BarChartFormatter: NSObject, IAxisValueFormatter
{
var matches: [String]! = ["Lost", "Drawn", "Won"]
public func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
return matches[Int(value)]
}
}
You can set the color and fonts using the BarChartData class object. For your case, it is chartData
Follow below code in order to set the required fonts and color of labels.
chartData.setValueFont(UIFont.systemFont(ofSize: 14.0))
chartData.setValueTextColor(UIColor.white)
In case you want to show the label within the bar then set your BarChartView object property drawValueAboveBarEnabled to false. It will render your labels within the bars.
barChartView.drawValueAboveBarEnabled = false

How to set correct labels is iOS Charts bar chart and colour columns to suit?

I have an iOS Chart, as per the image below, and the labels are showing incorrectly (or not what I want).
As you can see they both say 'Games Played' and are the same colour, as is each bar in my graph.
How can I change the colour of each bar and show the correct respective labels, 'Won', 'Drawn', 'Lost'?
This is my code:
override func viewDidLoad() {
super.viewDidLoad()
let results = ["Won", "Drawn", "Lost"]
let games = [totalWins, totalDraws, totalLosses]
setChart(dataPoints: results, values: games)
}
func setChart(dataPoints: [String], values: [Double]){
let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()
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)
formato.stringForValue (Double(i), axis: xaxis)
}
xaxis.valueFormatter = formato
barChartView.xAxis.valueFormatter = xaxis.valueFormatter
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Games Played")
let chartData = BarChartData(dataSets: [chartDataSet])
chartData.addDataSet(chartDataSet)
barChartView.data = chartData
barChartView.leftAxis.forceLabelsEnabled = true
barChartView.rightAxis.forceLabelsEnabled = true
barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.granularity = 1.0
barChartView.leftAxis.drawGridLinesEnabled = false
barChartView.rightAxis.drawGridLinesEnabled = false
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.rightAxis.enabled = false
barChartView.drawGridBackgroundEnabled = false
self.barChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
}
Simply add chartDataSet.colors = ChartColorTemplates.material() or you can add your array of UIColor in order to customise according to your need.

ios charts not displaying line/bar in charts

I am working on ios-charts by Daniel Gindi on swift 3.0. I have written following code for bar charts
var dataEntries: [BarChartDataEntry] = []
for i in 0..<dateTime.count {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy hh:mm:ss aa"
let dateObj = dateFormatter.date(from: dateTime[i])
let timeIntervalForDate = dateObj!.timeIntervalSince1970
let dataEntry = BarChartDataEntry(x: Double(timeIntervalForDate), y: Double(readings[i]))
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units")
let chartData = BarChartData(dataSet: chartDataSet)
self.ChartsView.data = chartData
i get following result in emulator:
you can see no red line reflecing my values. I even zoomed to charts but nothing was shown.
I also tried line chart with sample values. Here is the code:
let dollars1 = [20.0, 4.0, 6.0, 3.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
var yValues : [ChartDataEntry] = [ChartDataEntry]()
for i in 0 ..< months.count {
yValues.append(ChartDataEntry(x: Double(i + 1), y: dollars1[i]))
}
let LineData = LineChartData()
let ds = LineChartDataSet(values: yValues, label: "Months")
LineData.addDataSet(ds)
self.ChartsView.data = LineData
Its result is even more weird. No grid lines are shown either in this chart. Here is the image.
I am not sure what is wrong with these graphs. Am I missing something. So far i am unable to look any furthur as most solutions are using old version of charts(or may be it is something else i am not aware). Please guide me to proper direction. Thanks
I am struggling with Version 3.0 and Swift 3 and the lack of documentation... May I point you to the best text on the subject which can be found here
Xvals as Parameters are gone, instead you use two-dimensional data on axis
Regarding your problem with timevalues.. you could use the "timeIntervalSince1970" of the date-object and format things with an extension
return dateFormatter.string(from: Date(timeIntervalSince1970: value))
all of which is to be found at the link mentioned above
There is a bug in ios-charts try to use index of timestamp rather than using timestamp or date to show on the x-axis.
// i is the index of that timestamp in data.
let dataEntry = BarChartDataEntry(x: i, y: Double(readings[i]))
hey nothing is disabled in iOS charts everything is working fine..Here is the code that I have used in my app to display horizontal chart as well as vertical chart hope it helps to anyone who is stucked on IOS chart...stay tune with StackOverflow... enjoy coding :)
import UIKit
import Charts
class DashboardViewController: UIViewController, ChartViewDelegate
{
#IBOutlet weak var barview: BarChartView!
#IBOutlet weak var horizontalview: HorizontalBarChartView!
var attendencelabels = [String]()
let Present = [60.0, 60.0]
let Absent = [20.0,40.0]
var subjects : [String]!
var maxUnits : Double!
override func viewDidLoad() {
super.viewDidLoad()
barview.delegate = self
barview.noDataText = "You need to provide data for the chart."
barview.chartDescription?.text = ""
attendencelabels.append("March")
attendencelabels.append("April")
subjects = ["Physics","Chemistry","Biology","English","Maths"]
horizontalview.delegate = self
var marks = [60.0,70.0,60.0,80.0,90.0]
maxUnits = marks.max()
setHorizontalChart(dataPoints: subjects, values: marks)
//legend
let legend = barview.legend
legend.enabled = true
legend.horizontalAlignment = .center
legend.verticalAlignment = .bottom
legend.orientation = .horizontal
legend.drawInside = false
legend.yOffset = 10.0;
legend.xOffset = 10.0;
legend.yEntrySpace = 0.0;
let xaxis = barview.xAxis
xaxis.valueFormatter = DefaultAxisValueFormatter.self as! IAxisValueFormatter
xaxis.drawGridLinesEnabled = true
xaxis.labelPosition = .top
xaxis.centerAxisLabelsEnabled = true
xaxis.valueFormatter = IndexAxisValueFormatter(values:self.attendencelabels)
xaxis.granularity = 1
let leftAxisFormatter = NumberFormatter()
leftAxisFormatter.maximumFractionDigits = 1
let yaxis = barview.leftAxis
yaxis.spaceTop = 0.35
yaxis.axisMinimum = 0
yaxis.drawGridLinesEnabled = false
barview.rightAxis.enabled = false
setChart()
}
func setChart() {
barview.noDataText = "You need to provide data for the chart."
var dataEntries: [BarChartDataEntry] = []
var dataEntries1: [BarChartDataEntry] = []
for i in 0..<self.attendencelabels.count
{
let dataEntry = BarChartDataEntry(x: Double(i) , y: self.Present[i])
dataEntries.append(dataEntry)
let dataEntry1 = BarChartDataEntry(x: Double(i) , y: self.self.Absent[i])
dataEntries1.append(dataEntry1)
//stack barchart
//let dataEntry = BarChartDataEntry(x: Double(i), yValues: [self.unitsSold[i],self.unitsBought[i]], label: "groupChart")
}
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Working Days")
let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: "Present Days")
let dataSets: [BarChartDataSet] = [chartDataSet,chartDataSet1]
chartDataSet.colors = [UIColor(red: 0/255, green: 255/255, blue: 25/255, alpha: 1)]
chartDataSet1.colors = [UIColor(red: 255/255, green: 0/255, blue: 61/255, alpha: 1)]
//chartDataSet.colors = ChartColorTemplates.colorful()
//let chartData = BarChartData(dataSet: chartDataSet)
let chartData = BarChartData(dataSets: dataSets)
let groupSpace = 0.3
let barSpace = 0.05
let barWidth = 0.3
// (0.3 + 0.05) * 2 + 0.3 = 1.00 -> interval per "group"
let groupCount = self.attendencelabels.count
let startYear = 0
chartData.barWidth = barWidth;
barview.xAxis.axisMinimum = Double(startYear)
let gg = chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
print("Groupspace: \(gg)")
barview.xAxis.axisMaximum = Double(startYear) + gg * Double(groupCount)
chartData.groupBars(fromX: Double(startYear), groupSpace: groupSpace, barSpace: barSpace)
//chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
barview.notifyDataSetChanged()
barview.data = chartData
//background color
barview.backgroundColor = UIColor.white
//chart animation
barview.animate(xAxisDuration: 1.5, yAxisDuration: 1.5, easingOption: .linear)
}
func setHorizontalChart(dataPoints: [String], values: [Double]) {
horizontalview.noDataText = "You need to provide data for the chart."
let formato: horizontalbarformatter = horizontalbarformatter()
let xaxiss: XAxis = XAxis()
var dataEntriesss: [BarChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntryy = BarChartDataEntry(x: Double(Int(i)), y: values[i])
dataEntriesss.append(dataEntryy)
formato.stringForValue(Double(i), axis: xaxiss)
}
xaxiss.valueFormatter = formato
let chartHorizontalDataSet = BarChartDataSet(values: dataEntriesss, label: "Marks")
let horizontalchartData = BarChartData(dataSet: chartHorizontalDataSet)
chartHorizontalDataSet.colors = ChartColorTemplates.colorful()
horizontalview.xAxis.valueFormatter = xaxiss.valueFormatter
horizontalview.data = horizontalchartData
horizontalview.backgroundColor = UIColor.white
horizontalview.descriptionText = ""
horizontalview.xAxis.labelPosition = .bottom
horizontalview.leftAxis.axisMinimum = 0
horizontalview.leftAxis.axisMaximum = maxUnits + 1
//barChartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0)
horizontalview.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInBounce)
let ll = ChartLimitLine(limit: 10.0, label: "Target")
horizontalview.rightAxis.addLimitLine(ll)
}
func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
print("\(entry.y) in \(attendencelabels[Int(entry.x)])")
}
}

How to update data in iOS-Charts?

I have tried to update the data in my barChart, when i passed another dataSet which contains more data points everything goes well, but when i passed another dataSet with a lower data points, the app crashes.
I have also tried putting the barchartView.notifyDataSetChanged() after the line chart.DataSet.color but still crashes, maybe is the wrong place, but i have tried putting the notifyDataSetChanged in many places.
I let you my code, what i do when change the dataSet values is just calling the setChart method and pass the new values array as parameter.
func setChart(values: [Double]) {
let formato:BarChartFormatter = BarChartFormatter()
formato.setArray(self.listadoLabels)
let xaxis:XAxis = XAxis()
barChartView.noDataText = "You need to provide data for the chart."
max = values.maxElement()
var dataEntries: [BarChartDataEntry] = []
for i in 0..<values.count {
let dataEntry = BarChartDataEntry(x: Double(i), y:values[i])
dataEntries.append(dataEntry)
formato.stringForValue(Double(i), axis: xaxis)
}
xaxis.valueFormatter = formato
let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units")
chartDataSet.colors = ChartColorTemplates.joyful()
barChartView.notifyDataSetChanged()
barChartView.fitBars = true
barChartView.xAxis.valueFormatter = xaxis.valueFormatter
barChartView.xAxis.labelPosition = .Bottom
if(values.count > 5){barChartView.zoom(scaleX: 17.0, scaleY: 1.0, x: 0, y: 0)}
barChartView.xAxis.granularityEnabled = true
barChartView.xAxis.granularity = 1.0
barChartView.leftAxis.axisMinimum = 0
barChartView.leftAxis.axisMaximum = max != nil ? max + (2 * max/10) : 5
barChartView.rightAxis.enabled = false
barChartView.drawValueAboveBarEnabled = true
barChartView.descriptionText = ""
barChartView.xAxis.drawGridLinesEnabled = false
barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
let chartData = BarChartData()
chartData.addDataSet(chartDataSet)
barChartView.data?.notifyDataChanged()
barChartView.data = chartData
}
The console shows "fatal error: index out of range".
Hope someone can help, thanks.

Resources