How to draw text parallel to Bar of BarChartView? - ios

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)

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 set BarChartDataEntry labels (String not Double) not xaxis labels

Hi all i need help i want to format BarChartDataEntry labels as shown in image.
My Code
var dataEntries: [BarChartDataEntry] = []
var dataEntriesBottom: [BarChartDataEntry] = []
for i in 0..<goals.count {
let dataEntry = BarChartDataEntry(x: Double(i), y: Double(goals[i]))
dataEntries.append(dataEntry)
}
let chartDataSet = BarChartDataSet(entries: dataEntries, label: "")
chartDataSet.colors = [.systemGreen]
let chartData = BarChartData(dataSet: chartDataSet)
chartData.barWidth = 0.4
chartView.xAxis.drawAxisLineEnabled = false
chartView.leftAxis.drawAxisLineEnabled = false
chartView.xAxis.drawGridLinesEnabled = false
chartView.rightAxis.drawAxisLineEnabled = false
chartView.leftAxis.drawLabelsEnabled = false
chartView.rightAxis.drawLabelsEnabled = false
chartView.leftAxis.drawGridLinesEnabled = false
chartView.rightAxis.drawGridLinesEnabled = false
chartView.xAxis.enabled = false
chartView.xAxis.drawLabelsEnabled = false
chartView.xAxis.granularity = 0
self.chartView.animate(yAxisDuration: 1.0)
self.chartView.legend.enabled = false
chartView.data = chartData
try something like this:
let myFormatter = NumberFormatter()
myFormatter.numberStyle = .decimal
myFormatter.maximumFractionDigits = 0
chartData.setValueFormatter(DefaultValueFormatter(formatter: myFormatter))

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
}

Swift Chart months at bottom

I'm integrating Chart in my app.
Using https://github.com/danielgindi/Charts
this have achieved:
Expected Result:
Code:
let leftAxisFormatter = NumberFormatter()
leftAxisFormatter.minimumFractionDigits = 0
leftAxisFormatter.maximumFractionDigits = 1
leftAxisFormatter.negativePrefix = " $"
leftAxisFormatter.positivePrefix = " $"
chartView.xAxis.gridLineDashPhase = 0
chartView.leftAxis.enabled = false
chartView.xAxis.enabled = false
let rightAxis = chartView.rightAxis
rightAxis.enabled = true
rightAxis.labelFont = .systemFont(ofSize: 10)
rightAxis.labelCount = 4
rightAxis.valueFormatter = DefaultAxisValueFormatter(formatter: leftAxisFormatter)
rightAxis.axisMinimum = 0
rightAxis.drawZeroLineEnabled=true
rightAxis.labelPosition = .insideChart
chartView.leftAxis.drawZeroLineEnabled = true
chartView.legend.enabled = false
chartView.leftAxis.drawAxisLineEnabled = false
chartView.leftAxis.drawGridLinesEnabled = false
chartView.rightAxis.drawAxisLineEnabled = false
chartView.rightAxis.drawGridLinesEnabled = false
chartView.xAxis.drawAxisLineEnabled = false
chartView.xAxis.drawGridLinesEnabled = false
let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values:months)
chartView.xAxis.granularity = 1
What are other properties to achieve White vertical line on graph & Bottom Months in bottom.
Thanks in advance.
use lineChart.xAxis.labelPosition = .bottom // LineChart
lineChart.chartDescription?.enabled = false
lineChart.dragEnabled = false
lineChart.setScaleEnabled(false)
lineChart.pinchZoomEnabled = false
lineChart.rightAxis.enabled = false
lineChart.legend.form = .default
lineChart.legend.formSize = 0.0
lineChart.xAxis.axisMinimum = 0.0
lineChart.leftAxis.axisMinimum = 0.0
lineChart.xAxis.axisMaximum = 12.0
lineChart.leftAxis.axisMaximum = 100.0
lineChart.gridBackgroundColor = .clear
lineChart.xAxis.labelPosition = .bottom
lineChart.xAxis.labelFont = UIFont.RobotoRegularFontWithSize(size: 11)
lineChart.xAxis.labelTextColor = UIColor.clear
lineChart.leftAxis.labelTextColor = .clear
lineChart.leftAxis.labelFont = UIFont.RobotoRegularFontWithSize(size: 11)
lineChart.highlightPerTapEnabled = true
lineChart.leftAxis.drawAxisLineEnabled = true
lineChart.leftAxis.drawGridLinesEnabled = false
lineChart.rightAxis.drawAxisLineEnabled = false
lineChart.rightAxis.drawLabelsEnabled = false
lineChart.xAxis.drawGridLinesEnabled = false
lineChart.extraRightOffset = 15*screenWidthFactor
lineChart.drawMarkers = true
lineChart.pinchZoomEnabled = true
lineChart.doubleTapToZoomEnabled = true

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