show all axis lines without zoom linechart - ios

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
}

Related

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

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
}

How to draw text parallel to Bar of BarChartView?

I am trying to achieve the functionality to show the win and loss percent of every month parallel to the bar. Please provide any suggestion.
I am using danielgindi/Charts
I am trying to achive the this functinality.
here is the chart setup code:
chartView.legend.enabled = true
chartView.chartDescription?.enabled = false
chartView.maxVisibleCount = 12
chartView.drawBarShadowEnabled = false
chartView.drawValueAboveBarEnabled = false
chartView.delegate = self
chartView.dragEnabled = true
chartView.doubleTapToZoomEnabled = false
chartView.pinchZoomEnabled = true
chartView.noDataTextColor = .black
chartView.highlightFullBarEnabled = true
chartView.drawGridBackgroundEnabled = false
chartView.leftAxis.enabled = false
chartView.leftAxis.drawGridLinesEnabled = false
chartView.rightAxis.enabled = false
chartView.rightAxis.drawGridLinesEnabled = false
chartView.xAxis.enabled = true
chartView.xAxis.drawGridLinesEnabled = false
chartView.xAxis.drawAxisLineEnabled = false
chartView.xAxis.labelPosition = .bottom
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: months)
chartView.xAxis.setLabelCount(months.count, force: false)
chartView.xAxis.granularity = 1
let l = chartView.legend
l.horizontalAlignment = .center
l.verticalAlignment = .bottom
l.orientation = .horizontal
l.drawInside = false
l.xEntrySpace = 5
l.yEntrySpace = 2
l.yOffset = 5
l.xOffset = 20
here i am assigning the value to chart
let yVals = (0..<data.count).map { (i) -> BarChartDataEntry in
let val1 = Double(data[i].ownopportunityOwn.roundToOneDigitCroreValue)
let val2 = Double(data[i].ownopportunityAssistby.roundToOneDigitCroreValue)
return BarChartDataEntry(x: Double(i), yValues: [val1, val2])
}
let set = BarChartDataSet(values: yVals, label: "")
set.drawIconsEnabled = false
set.colors = [AppColors.Graph_LightGreenColor,AppColors.Graph_PurpleColor]
set.roundedCorners = [.topLeft,.topRight]
let data = BarChartData(dataSet: set)
data.setValueFont(.systemFont(ofSize: 7, weight: .bold))
data.setValueFormatter(DefaultValueFormatter(formatter: formatter))
data.setValueTextColor(.white)
chartView.fitBars = true
chartView.data = data
var array = [LegendEntry]()
var legendValueArray = [(title: DashboardConstant.K_OWN_WINS.value, Color: AppColors.Graph_LightGreenColor),(title: DashboardConstant.K_ASSISTED_BY_WIN.value, Color: AppColors.Graph_PurpleColor)]
for object in legendValueArray {
array.append( LegendEntry(label: object.title, form: .square, formSize: 10, formLineWidth: 1, formLineDashPhase: 1, formLineDashLengths: nil, formColor: object.Color))
}
self.chartView.legend.setCustom(entries: array)
self.chartView.fitScreen()
self.chartView.notifyDataSetChanged()
chartView.animate(xAxisDuration: 3, yAxisDuration: 3)

How can I show first value and last value in line Chart

I'm using charts library and i'm trying to add first value and last value on line chart graph.Please let me know how can I achieve it. I have tried customising drawValue method in linechartrenderer but didn't worked.
Here is my code
var months = ["Dec 15", "Jun 16", "Dec 16", "Jun 17", "Dec 17", "Jun 18"]
var unitsSold = [50.0, 25.0, 50.0, 75.0, 100.0, 75.0]
Viewdidload:
setChart(dataPoints: months, values: unitsSold)
Method:
func setChart(dataPoints: [String], values: [Double]) {
var dataEntries: [ChartDataEntry] = []
for i in 0..<dataPoints.count {
let dataEntry = ChartDataEntry(x: Double(i), y: values[i], data: dataPoints[i] as AnyObject)
dataEntries.append(dataEntry)
}
let chartDataSet = LineChartDataSet(values: dataEntries, label: nil)
chartDataSet.setColor(UIColor(red: 53/255, green: 85/255, blue: 123/255, alpha: 1))
chartDataSet.circleRadius = 5
chartDataSet.circleHoleRadius = 2
chartDataSet.drawValuesEnabled = false
chartDataSet.drawCirclesEnabled = false
let chartData = LineChartData(dataSets: [chartDataSet])
defaultChartView.data = chartData
defaultChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: months)
defaultChartView.xAxis.labelPosition = .bottom
defaultChartView.xAxis.drawGridLinesEnabled = false
//lineChartView.xAxis.avoidFirstLastClippingEnabled = true
defaultChartView.xAxis.axisMinimum = 0
defaultChartView.xAxis.granularity = 1
defaultChartView.rightAxis.drawAxisLineEnabled = false
defaultChartView.rightAxis.drawLabelsEnabled = false
defaultChartView.rightAxis.enabled = false
defaultChartView.leftAxis.drawAxisLineEnabled = false
defaultChartView.leftAxis.axisMinimum = 0.0
defaultChartView.leftAxis.drawLabelsEnabled = false
//lineChartView.leftAxis.drawGridLinesEnabled = false
//lineChartView.leftAxis.granularityEnabled = false
defaultChartView.pinchZoomEnabled = true
defaultChartView.doubleTapToZoomEnabled = true
defaultChartView.legend.enabled = false
defaultChartView.chartDescription?.text = " "
}
viewDidLoad:
guard let firstMonth = months.first, let lastMonth = months.last else {
return
}
let myMonths = [firstMonth, lastMonth]
guard let firstValue = unitsSold.first, let lastValue = unitsSold.last else {
return
}
let myValues = [firstValue, lastValue]
setChart(dataPoints: myMonths, values: myValues)
Solution is go to linechartrenderer file and replace drawValues method
open override func drawValues(context: CGContext)
{
guard
let dataProvider = dataProvider,
let lineData = dataProvider.lineData
else { return }
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
var dataSets = lineData.dataSets
let phaseY = animator.phaseY
var pt = CGPoint()
for i in 0 ..< dataSets.count
{
guard let dataSet = dataSets[i] as? ILineChartDataSet else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let valueToPixelMatrix = trans.valueToPixelMatrix
let iconsOffset = dataSet.iconsOffset
// make sure the values do not interfear with the circles
var valOffset = Int(dataSet.circleRadius * 1.75)
if !dataSet.isDrawCirclesEnabled
{
valOffset = valOffset / 2
}
_xBounds.set(chart: dataProvider, dataSet: dataSet, animator: animator)
for j in stride(from: _xBounds.min, through: min(_xBounds.min + _xBounds.range, _xBounds.max), by: 1)
{
guard let e = dataSet.entryForIndex(j) else { break }
if(j == 0 || j == dataSet.entryCount - 1)
{
pt.x = CGFloat(e.x)
pt.y = CGFloat(e.y * phaseY)
pt = pt.applying(valueToPixelMatrix)
if (!viewPortHandler.isInBoundsRight(pt.x))
{
break
}
if (!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))
{
continue
}
if dataSet.isDrawValuesEnabled {
ChartUtils.drawText(
context: context,
text: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
point: CGPoint(
x: pt.x,
y: pt.y - CGFloat(valOffset) - valueFont.lineHeight),
align: .center,
attributes: [NSAttributedStringKey.font: valueFont, NSAttributedStringKey.foregroundColor: dataSet.valueTextColorAt(j)])
}
if let icon = e.icon, dataSet.isDrawIconsEnabled
{
ChartUtils.drawImage(context: context,
image: icon,
x: pt.x + iconsOffset.x,
y: pt.y + iconsOffset.y,
size: icon.size)
}
}
else{
}
}
}
}
}
Set below property of X axis
barChartView.xAxis.setLabelCount(2, force: true)

iOS Charts - How to set the y values under the x axis

I'm using the danielgindi/Charts library and I'm trying to put the Y Value under the X axis.
At the moment I have this:
And I need this:
My code:
private func setupBarChart(){
var barChart = BarChartView(frame: frame)
barChartContainer.addSubview(barChart)
let labels = ["Ericsson", "Siemens", "Huawei", "Ericsson", "Siemens"]
barChartContainer.addConstraintsWithFormat("H:|[v0]|", views: barChart)
barChartContainer.addConstraintsWithFormat("V:|[v0]|", views: barChart)
let entry1 = BarChartDataEntry(x: 0, y: 3670)
let set1 = BarChartDataSet(values: [entry1], label: labels[0])
set1.setColor(UIColor.cnBlue)
let entry2 = BarChartDataEntry(x: 1, y: 2292)
let set2 = BarChartDataSet(values: [entry2], label: labels[1])
set2.setColor(UIColor.cnBlue)
let entry3 = BarChartDataEntry(x: 2, y: 3670)
let set3 = BarChartDataSet(values: [entry3], label: labels[2])
set3.setColor(UIColor.cnBlue)
let entry4 = BarChartDataEntry(x: 3, y: 2292)
let set4 = BarChartDataSet(values: [entry4], label: labels[3])
set4.setColor(UIColor.cnBlue)
let entry5 = BarChartDataEntry(x: 4, y: 675)
let set5 = BarChartDataSet(values: [entry5], label: labels[4])
set5.setColor(UIColor.cnBlue)
let data = BarChartData(dataSets: [set1, set2, set3, set4, set5])
barChart.data = data
barChart.drawGridBackgroundEnabled = false
barChart.drawValueAboveBarEnabled = false
barChart.drawBordersEnabled = false
barChart.legend.enabled = false
barChart.chartDescription?.text = "Sites per technology"
barChart.chartDescription?.textAlign = .center
barChart.chartDescription?.position = CGPoint(x: barChartContainer.bounds.width/2, y: 0)
barChart.xAxis.labelPosition = .bottom
barChart.xAxis.drawGridLinesEnabled = false
barChart.xAxis.wordWrapEnabled = true
barChart.xAxis.labelFont = .cnFont(ofSize: 14, weight: .semibold)
barChart.xAxis.valueFormatter = DefaultAxisValueFormatter(block: {(index, _) in
return labels[Int(index)]
})
barChart.leftAxis.enabled = false
barChart.rightAxis.enabled = false
barChart.drawValueAboveBarEnabled = false
barChart.doubleTapToZoomEnabled = false
barChart.pinchZoomEnabled = false
barChart.scaleXEnabled = false
barChart.scaleYEnabled = false
barChart.setExtraOffsets(left: 10, top: 10, right: 10, bottom: 10)
barChart.fitBars = true
barChart.animate(xAxisDuration: 1, yAxisDuration: 1, easingOption: .easeInOutCirc)
}
Do I have to make a custom AxisRenderer and if so can you give me some leads on this? I have been searching for examples but I still haven't been able to understand how to get what I need with the renderer.
Thank you in advance!
You can implement IAxisValueFormatter protocol this way
struct Label {
var text: String
var value: Double
}
public class DayAxisValueFormatter: NSObject, IAxisValueFormatter {
var xToY = [Double: Label]()
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return "\(xToY[value]!.text ),\n\(xToY[value]!.value)"
}
}
Then assign this formatter to x axis
let f = DayAxisValueFormatter(chart: chartView)
f.xToY = [
0: Label(text: "Biemens", value: 6354),
1: Label(text: "Siemens", value: 2344),
2: Label(text: "Ericsson", value: 2345),
3: Label(text: "Huawei", value: 5241),
4: Label(text: "Shmericsson", value: 3525)
]
barChart.xAxis.valueFormatter = f

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.

Resources