How do I draw yaxis min value as different color on certain limit? - ios

I am using iOS Charts to draw linechart but unable to draw the same graph as shown below in the image. I tried by setting leftAxis.axisMinimum = minValue but it also not working. If the given value is minimum on certain limit it should show in red color as shown in attached image.
func setLineChartWithDateFormat(graphPoints: [GraphPoints], linePosition: CGFloat, minValue: Double = 0, fillColor: UIColor = UIColor(red: 158.0/255.0, green: 188.0/255.0, blue: 136.0/255.0, alpha: 1)) {
var referenceTimeInterval: TimeInterval = 0
if let minTimeInterval = (graphPoints.map { ($0.getDateFromDateTime?.timeIntervalSince1970 ?? 0) }).min() {
referenceTimeInterval = minTimeInterval
}
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.dateFormat = "MMM dd"
let xValuesNumberFormatter = ChartXAxisWithFormatter(referenceTimeInterval: referenceTimeInterval, dateFormatter: formatter)
// Define chart entries
var entries = [ChartDataEntry]()
var xAxisValues = [CGFloat]()
for object in graphPoints {
let timeInterval = object.getDateFromDateTime?.timeIntervalSince1970 ?? 0
let xValue = (timeInterval - referenceTimeInterval) / (3600 * 24)
xAxisValues.append(CGFloat(xValue))
let yValue = object.price ?? 0
let entry = ChartDataEntry(x: xValue, y: yValue)
entry.setValue(object.getDateFromDateTime, forKey: "data")
entries.append(entry)
}
var minValue = xAxisValues.min()
let chartDataSet = LineChartDataSet(entries: entries, label: "BPM")
chartDataSet.fillColor = fillColor
/// Data object that encapsulates all data associated with a LineChart.
let chartData = LineChartData()
chartData.addDataSet(chartDataSet)
chartData.setDrawValues(false)
chartDataSet.drawCirclesEnabled = false
chartDataSet.mode = .linear
chartDataSet.colors = [.white]
chartDataSet.fillFormatter = LineChartFillFormatter(value: minValue ?? 0)
// let gradientColors = [gradientColor1.cgColor, gradientColor2.cgColor] as CFArray
// let colorLocations: [CGFloat] = [0.7,0.0]
// guard CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors, locations: colorLocations) != nil else {
// print("Gradient Error")
// return
// }
chartDataSet.drawFilledEnabled = true
chartDataSet.fillAlpha = 1
chartDataSet.setDrawHighlightIndicators(true)
chartDataSet.drawHorizontalHighlightIndicatorEnabled = false
// lineChart.leftAxis.axisMinimum = minValue
///x axis for chart view
let xAxis: XAxis = self.lineChart.xAxis
xAxis.labelPosition = .bottomInside
xAxis.drawGridLinesEnabled = true //true, if want x Axis grid lines
xAxis.valueFormatter = xValuesNumberFormatter
xAxis.gridColor = gridColor
xAxis.axisLineColor = gridColor
xAxis.labelFont = BSFonts.getFontWithSize(fontType: .iBMPlexSansCond, fontSize: BSFontSize.small)
xAxis.labelTextColor = axisTextColor
xAxis.labelPosition = .bottom
xAxis.spaceMin = 0.5
xAxis.drawAxisLineEnabled = false
xAxis.drawLimitLinesBehindDataEnabled = true
xAxis.granularityEnabled = true
// xAxis.granularity = 2
xAxis.labelWidth = UIDevice.current.isIPad ? 30 : 20
// xAxis.labelCount = 4
///right axis for chart view
let rightAxis: YAxis = lineChart.rightAxis
rightAxis.enabled = false
///y axis of chart view
let leftAxis: YAxis = lineChart.leftAxis
leftAxis.labelPosition = .insideChart
leftAxis.drawGridLinesEnabled = true //true, if want y axis grid lines
leftAxis.drawLabelsEnabled = true
leftAxis.gridColor = gridColor
leftAxis.axisLineColor = gridColor
leftAxis.labelFont = BSFonts.getFontWithSize(fontType: .iBMPlexSansCond, fontSize: BSFontSize.small)
leftAxis.labelTextColor = axisTextColor
leftAxis.labelPosition = .outsideChart
//leftAxis.spaceBottom = 0.3
leftAxis.drawAxisLineEnabled = false
leftAxis.labelCount = 4
/// The data for the chart
lineChart.data = chartData
lineChart.doubleTapToZoomEnabled = false
lineChart.data?.highlightEnabled = true
}

Related

show all axis lines without zoom linechart

Hello i want to see all records in line-chart but without zoom, at this time if i don't zoom it does not show lines u can see in screenshots please guide me This image is Without Zoom, for example if there are 100 records i want to draw all lines but without zoom i need to see them
After zoom i can see lines
this is how i set data
func setDataCount() {
// lineChartView.clear()
var systolicArray :[ChartDataEntry] = []
var diastolicArray:[ChartDataEntry] = []
var pulseArray:[ChartDataEntry] = []
systolicArray.removeAll()
diastolicArray.removeAll()
pulseArray.removeAll()
let systolicSortingByDate = systolic.sorted(by: { $0.date > $1.date})
// print("---Dumb:\(dump(systolicSortingByDate))")
for data in systolic {
let timeIntervalForDate: TimeInterval = AppData.stringToDate(date: data.date).timeIntervalSince1970
let systolicChart = ChartDataEntry(x: Double(timeIntervalForDate), y: Double(data.systolicReading), icon: #imageLiteral(resourceName: "editprofile"))
systolicArray.append(systolicChart)
}
for data in diastolic {
let timeIntervalForDate: TimeInterval = AppData.stringToDate(date: data.date).timeIntervalSince1970
let diastolicChart = ChartDataEntry(x: Double(timeIntervalForDate), y: Double(data.diastolicReading), icon: #imageLiteral(resourceName: "editprofile"))
diastolicArray.append(diastolicChart)
}
for data in pulse {
let timeIntervalForDate: TimeInterval = AppData.stringToDate(date: data.date).timeIntervalSince1970
let diastolicChart = ChartDataEntry(x: Double(timeIntervalForDate), y: Double(data.pulseReading), icon: #imageLiteral(resourceName: "editprofile"))
pulseArray.append(diastolicChart)
}
print("SystolicCount:\(systolic.count)")
let set1 = LineChartDataSet(values: systolicArray, label: "Systolic")
set1.drawIconsEnabled = false
set1.highlightLineDashLengths = [5, 2.5]
set1.setColor(UIColor().HexToColor(hexString: "ff8a00"))
set1.setCircleColor((UIColor().HexToColor(hexString: "ff8a00")))
set1.lineWidth = 4
set1.circleRadius = 3
set1.drawCircleHoleEnabled = true
set1.valueFont = .systemFont(ofSize: 9)
set1.formLineDashLengths = [5, 2.5]
set1.formLineWidth = 2
set1.formSize = 15
let set2 = LineChartDataSet(values: diastolicArray, label: "Diastolic")
set2.drawIconsEnabled = false
set2.setColor(.black)
set2.setCircleColor(.black)
set2.lineWidth = 4
set2.circleRadius = 3
set2.drawCircleHoleEnabled = true
set2.valueFont = .systemFont(ofSize: 9)
set2.formLineDashLengths = [5, 2.5]
set2.formLineWidth = 2
set2.formSize = 15
let set3 = LineChartDataSet(values: pulseArray, label: "Pulse")
set3.drawIconsEnabled = false
set3.setColor(UIColor().HexToColor(hexString: "e83636"))
set3.setCircleColor(UIColor().HexToColor(hexString: "e83636"))
set3.lineWidth = 4
set3.circleRadius = 3
set3.drawCircleHoleEnabled = true
set3.valueFont = .systemFont(ofSize: 9)
set3.formLineDashLengths = [5, 2.5]
set3.formLineWidth = 2
set3.formSize = 15
lineChartView.rightAxis.enabled = true
lineChartView.xAxis.setLabelCount(systolicArray.count, force: false)
let data = LineChartData(dataSets: [set1,set2,set3])
lineChartView.data = data
let xAxisValue = lineChartView.xAxis
xAxisValue.valueFormatter = axisFormatDelegate
xAxisValue.setLabelCount(4, force: false)
lineChartView.animate(xAxisDuration: 3, yAxisDuration: 3)
// lineChartView.xAxis.granularity = 0.5
}

iOS-Charts grouped bar chart with size to fit

I recently added "barChartData.groupBars(fromX: 0, groupSpace: 0.5, barSpace: 0.03)" to my Bar Chart so that I don't have overlapping bars and I can't figure it out how to set the width to fit (no horizontal overflow)
func setupGroupedBarChartData(values1: [String], values2: [String], barLabel1: String, barLabel2: String, barColor1: UIColor, barColor2: UIColor) -> BarChartData {
let dataValues1 = values1.flatMap{ Double($0) }
let dataValues2 = values2.flatMap{ Double($0) }
var dataEntries1: [BarChartDataEntry] = []
var dataEntries2: [BarChartDataEntry] = []
for i in 0..<dataValues1.count {
let dataEntry1 = BarChartDataEntry(x: Double(i), y: dataValues1[i])
dataEntries1.append(dataEntry1)
let dataEntry2 = BarChartDataEntry(x: Double(i), y: dataValues2[i])
dataEntries2.append(dataEntry2)
}
let chartDataSet1 = BarChartDataSet(values: dataEntries1, label: barLabel1)
chartDataSet1.colors = [barColor1]
chartDataSet1.valueTextColor = AppColors.lightText
let chartDataSet2 = BarChartDataSet(values: dataEntries2, label: barLabel2)
chartDataSet2.colors = [barColor2]
chartDataSet2.valueTextColor = AppColors.lightText
var groupedDataSet : [BarChartDataSet] = [BarChartDataSet]()
groupedDataSet.append(chartDataSet1)
groupedDataSet.append(chartDataSet2)
let barChartData = BarChartData(dataSets: groupedDataSet)
barChartData.groupBars(fromX: 0, groupSpace: 0.5, barSpace: 0.03)
//display data as integer
let format = NumberFormatter()
format.generatesDecimalNumbers = false
let formatter = DefaultValueFormatter(formatter: format)
barChartData.setValueFormatter(formatter)
return barChartData
}
You can use like this :
You calculation will be like below :
// (barWidth + barSpace) * (no.of.bars) + groupSpace = 1.00 -> interval per "group"
In your code :
barChartData.groupBars(fromX: 0, groupSpace: 0.14, barSpace: 0.03)
barChartData.barWidth = 0.4
barChartView.xAxis.axisMinimum = 0
barChartView.xAxis.axisMaximum = 23

Charts, HorizontalBarChartView, how set values alignment = Center?

Swift 3.1, Charts, Multiple cells in tableView with HorizontalBarChartView.
Is it possible to align the value - centered?
Setup charts data:.
func refreshData() {
guard let item = self.item, !item.tasks.isEmpty else {
return
}
self.titleName.text = item.name
self.leftNameMargin.constant = CGFloat(30 * item.level)
self.titleName.textColor = UIColor(hexString: item.color)
let font = UIFont.systemFont(ofSize: 17.0, weight: UIFontWeightSemibold)
var colors: [UIColor] = []
var yValues: [Double] = []
var count = 0.0
for task in item.tasks {
count += Double(task.count)
yValues.append(Double(task.count))
colors.append(UIColor(hexString: task.valueColor))
}
let suffix = String(format: NSXLocalization.string(forKey: KEY_STR_PERCENT)) //fixes '%' duplication
let formatter = NumberFormatter()
formatter.roundingMode = .floor
formatter.numberStyle = .percent
formatter.positiveSuffix = suffix
formatter.negativeSuffix = suffix
formatter.zeroSymbol = ""
let dataEntry = BarChartDataEntry(x: 0.0, yValues: yValues.map { ($0 / count) })
let dataSet = BarChartDataSet(values: [dataEntry], label: nil)
dataSet.colors = colors
dataSet.valueTextColor = .white
dataSet.barBorderColor = .black
dataSet.barBorderWidth = 1.0
dataSet.drawValuesEnabled = true
dataSet.valueFormatter = DefaultValueFormatter(formatter: formatter)
let data = BarChartData(dataSets: [dataSet])
data.setValueFont(font)
data.setDrawValues(true)
data.highlightEnabled = true
self.chart.data = data
}
I Reviewed all internal methods in the charts, but never found a way to center the y values.

how to pass time as xAxis data value in method numberForPlot using core plot?

I need to create graph which is "Heart rate vs time". in xAxis I am showing time which is in format of "HH:mm:ss" and at y Axis its decimal value. My code is as below :
data source for graph:
var graphData:[(String,Double)] = []
let data = ("17:56:35",Double(65))
let data1 = ("18:04:13",Double(95))
let data2 = ("18:8:35",Double(25))
self.graphData.append(data)
self.graphData.append(data1)
self.graphData.append(data2)
Set up graph and plot data code:
func setGraph() {
let tts = CPTMutableTextStyle()
tts.fontSize = 75.0
tts.color = CPTColor(CGColor: UIColor.blackColor().CGColor)
tts.fontName = "HelveticaNeue-Bold"
self.graph.titleTextStyle = tts
self.graph.title = "Heart Rate vs Time"
self.graph.applyTheme(CPTTheme(named:kCPTPlainWhiteTheme))
let plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace!
plotSpace.allowsUserInteraction = false
let xRange = plotSpace.xRange.mutableCopy() as! CPTMutablePlotRange
xRange.locationDouble = Double(0)
xRange.lengthDouble = Double(1000)
plotSpace.xRange = xRange
let yRange = plotSpace.yRange.mutableCopy() as! CPTMutablePlotRange
yRange.locationDouble = Double(0)
yRange.lengthDouble = Double(210)
plotSpace.yRange = yRange
graph.addPlotSpace(plotSpace)
graph.plotAreaFrame!.paddingTop = 0
graph.plotAreaFrame!.paddingRight = 0
graph.plotAreaFrame!.paddingBottom = graphOffset
graph.plotAreaFrame!.paddingLeft = graphOffset
graph.plotAreaFrame!.masksToBorder = false
// Grid line styles
let majorLineStyle = CPTMutableLineStyle()
majorLineStyle.lineWidth = 0.75
majorLineStyle.lineColor = CPTColor.redColor()
let minorLineStyle = CPTMutableLineStyle()
minorLineStyle.lineWidth = 0.25
minorLineStyle.lineColor = CPTColor.blackColor()
//Axis Line colors
let axisLineStyle = CPTMutableLineStyle()
axisLineStyle.lineWidth = 2.0
axisLineStyle.lineColor = CPTColor.blackColor()
//Axis Label colors
let labelTextStyle = CPTMutableTextStyle()
labelTextStyle.textAlignment = CPTTextAlignment.Left
labelTextStyle.color = CPTColor.blackColor()
//Axis title color
let titleTextStyle = CPTMutableTextStyle()
titleTextStyle.textAlignment = CPTTextAlignment.Left
titleTextStyle.color = CPTColor.blackColor()
titleTextStyle.fontSize = 15
let dataSourceLinePlot = CPTScatterPlot()
let lineStyle = CPTMutableLineStyle()
lineStyle.lineWidth = 3.0
lineStyle.lineColor = CPTColor.blueColor()
dataSourceLinePlot.dataLineStyle = lineStyle
dataSourceLinePlot.identifier = kPlotIdentifier
// dataSourceLinePlot.dataSource = self
let xts = CPTMutableTextStyle()
xts.color = CPTColor(componentRed: 255.0, green: 255.0, blue: 255.0, alpha: 1.0)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let timeformatter = CPTTimeFormatter(dateFormatter: dateFormatter)
timeformatter.referenceDate = NSDate()
let axisSet = graph.axisSet as! CPTXYAxisSet!
let xAxis = axisSet.xAxis as CPTXYAxis!
xAxis.axisTitle = CPTAxisTitle(text: "Elapsed Time", textStyle: xts)
xAxis.labelFormatter = timeformatter
xAxis.majorGridLineStyle = majorLineStyle
xAxis.minorGridLineStyle = minorLineStyle
xAxis.majorIntervalLength = NSNumber(double: 60.0)
let yAxis = axisSet.yAxis as CPTXYAxis!
yAxis.axisTitle = CPTAxisTitle(text: "Heart Rate", textStyle: xts)
let axisFormatter = NSNumberFormatter()
axisFormatter.maximumFractionDigits = 0
axisFormatter.minimumIntegerDigits = 1
yAxis.labelFormatter = axisFormatter
yAxis.titleOffset = 35.0
yAxis.majorIntervalLength = 20
yAxis.majorGridLineStyle = majorLineStyle
yAxis.minorGridLineStyle = minorLineStyle
graph.addPlot(dataSourceLinePlot)
self.IBviewGraph.hostedGraph = self.graph
}
To plot data :
func setGraphData() {
dispatch_sync(dispatch_get_main_queue(), {
let plot = CPTScatterPlot()
plot.dataSource = self
let actualPlotStyle = plot.dataLineStyle!.mutableCopy() as! CPTMutableLineStyle
actualPlotStyle.lineWidth = 2.0
actualPlotStyle.lineColor = CPTColor(CGColor: (UIColor.yellowColor().CGColor))
plot.dataLineStyle = actualPlotStyle
plot.interpolation = .Linear
self.graph.addPlot(plot)
})
}
Data source methods
func numberOfRecordsForPlot(plot: CPTPlot) -> UInt {
return 3
}
func numberForPlot(plot: CPTPlot, field: UInt, recordIndex: UInt) -> AnyObject?{
var num = NSNumber()
let index = Int(recordIndex)
switch field {
case 0://xaxis
return graphData[index].0
case 1://yaxis
return graphData[index].1
default:
break
}
print("coordintes = ",num)
return num
}
My graph is drown but only yAxis points are correct , its not considering xAxis value and so because of that points are at wrong position in graph. I think the value I am passing in method numberForPlot for xAxis is wrong , but don't know how to pass it. Give me some solution.
The x-values in the graphData array are strings. Core Plot expects the datasource to return a numeric value for each index. It's reading the hour from the time string and using that for the x-value.
The x-axis is configured to display numbers in the range 0 to 1,000. Therefore, you need to convert the time data to a number in that range. Keep track of the reference date used to format the axis labels (i.e., store it in an instance variable) and use that to convert the time data to an offset in seconds from the reference date.

Graph plot reference point is changing

I have a weird issue. I have some data on graph and when new data arrives I am inserting that into graph. But issue is new data plotting is starting from first point of already drawn plot not from last point of plot. The console prints the correct point but the plotting starts from first point of already drawn plot not from last point of already drawn plot. My code for graph set up is here :Code for graph set up and Code for Axis animation
code :
func setGraph() {
let tts = CPTMutableTextStyle()
tts.fontSize = 75.0
tts.color = CPTColor(CGColor: UIColor.blackColor().CGColor)
tts.fontName = "HelveticaNeue-Bold"
self.graph.titleTextStyle = tts
self.graph.title = "Heart Rate vs Time"
self.graph.applyTheme(CPTTheme(named:kCPTPlainWhiteTheme))
let plotSpace = graph.defaultPlotSpace as! CPTXYPlotSpace!
plotSpace.allowsUserInteraction = false
let xRange = plotSpace.xRange.mutableCopy() as! CPTMutablePlotRange
xRange.locationDouble = Double(0)
xRange.lengthDouble = Double(kMaxDataPoints)
plotSpace.xRange = xRange
let yRange = plotSpace.yRange.mutableCopy() as! CPTMutablePlotRange
yRange.locationDouble = Double(0)
yRange.lengthDouble = Double(210)
plotSpace.yRange = yRange
graph.addPlotSpace(plotSpace)
graph.plotAreaFrame!.paddingTop = 0
graph.plotAreaFrame!.paddingRight = 0
graph.plotAreaFrame!.paddingBottom = graphOffset
graph.plotAreaFrame!.paddingLeft = graphOffset
graph.plotAreaFrame!.masksToBorder = false
// Grid line styles
let majorLineStyle = CPTMutableLineStyle()
majorLineStyle.lineWidth = 0.75
majorLineStyle.lineColor = CPTColor.redColor()
let minorLineStyle = CPTMutableLineStyle()
minorLineStyle.lineWidth = 0.25
minorLineStyle.lineColor = CPTColor.blackColor()
//Axis Line colors
let axisLineStyle = CPTMutableLineStyle()
axisLineStyle.lineWidth = 2.0
axisLineStyle.lineColor = CPTColor.blackColor()
//Axis Label colors
let labelTextStyle = CPTMutableTextStyle()
labelTextStyle.textAlignment = CPTTextAlignment.Left
labelTextStyle.color = CPTColor.blackColor()
//Axis title color
let titleTextStyle = CPTMutableTextStyle()
titleTextStyle.textAlignment = CPTTextAlignment.Left
titleTextStyle.color = CPTColor.blackColor()
titleTextStyle.fontSize = 15
let dataSourceLinePlot = CPTScatterPlot()
let lineStyle = CPTMutableLineStyle()
lineStyle.lineWidth = 3.0
lineStyle.lineColor = CPTColor.blueColor()
dataSourceLinePlot.dataLineStyle = lineStyle
dataSourceLinePlot.identifier = kPlotIdentifier
// dataSourceLinePlot.dataSource = self
let xts = CPTMutableTextStyle()
xts.color = CPTColor(componentRed: 255.0, green: 255.0, blue: 255.0, alpha: 1.0)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
let timeformatter = CPTTimeFormatter(dateFormatter: dateFormatter)
timeformatter.referenceDate = NSDate().dateByAddingTimeInterval(startTimeInterval)
currentdate = timeformatter.referenceDate
let axisSet = graph.axisSet as! CPTXYAxisSet!
let xAxis = axisSet.xAxis as CPTXYAxis!
xAxis.axisTitle = CPTAxisTitle(text: "Elapsed Time", textStyle: xts)
xAxis.labelFormatter = timeformatter
xAxis.majorGridLineStyle = majorLineStyle
xAxis.minorGridLineStyle = minorLineStyle
xAxis.majorIntervalLength = NSNumber(double: 30.0)
let yAxis = axisSet.yAxis as CPTXYAxis!
yAxis.axisTitle = CPTAxisTitle(text: "Heart Rate", textStyle: xts)
let axisFormatter = NSNumberFormatter()
axisFormatter.maximumFractionDigits = 0
axisFormatter.minimumIntegerDigits = 1
yAxis.labelFormatter = axisFormatter
yAxis.titleOffset = 35.0
yAxis.majorIntervalLength = 20
yAxis.majorGridLineStyle = majorLineStyle
yAxis.minorGridLineStyle = minorLineStyle
yAxis.axisConstraints = CPTConstraints(lowerOffset: 0.0)
graph.addPlot(dataSourceLinePlot)
self.IBviewGraph.hostedGraph = self.graph
setGraphData()
}
func setGraphData()
{
self.plot.dataSource = self
let actualPlotStyle = self.plot.dataLineStyle!.mutableCopy() as! CPTMutableLineStyle
actualPlotStyle.lineWidth = 2.0
actualPlotStyle.lineColor = CPTColor(CGColor: (UIColor.blueColor().CGColor))
self.plot.dataLineStyle = actualPlotStyle
self.plot.interpolation = .Curved
self.graph.addPlot(self.plot)
}
Now when i receive new data :
graphData.removeAtIndex(0)
plot.deleteDataInIndexRange(NSMakeRange(0, 1))
let location = currentIndex
let oldRange = CPTPlotRange(location: location , length: kMaxDataPoints)
let newRange = CPTPlotRange(location: location + 30, length: kMaxDataPoints)
CPTAnimation.animate(plotSpace, property: "xRange", fromPlotRange: oldRange, toPlotRange: newRange, duration: CGFloat(1.0 / kFrameRate))
graphData.append((newTime,data.1))
plot.insertDataAtIndex(UInt(graphData.count - 1), numberOfRecords: 1)

Resources