How to Add Strings on X Axis in iOS-Charts

How to use String values for X-Axis in Charts instead of doubles?

There's a protocol IAxisValueFormatter that you can implement and achieve your expected result.

EDIT:

How to use it

While initialising

chartView.xAxis.valueFormatter = self

and implementing protocol.

extension LineChart1ViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
let months = ["January","February","March","April","May","June","July","Auguest","September","October","November","December"]
return months[Int(value)]
}
}

How to add Strings on X Axis in iOS-charts?

I found the solution, maybe another one can solve this problem in a better way, without create a new class, well this is what I found:

First you nedd to create a new class, which will be your formatter class and add the IAxisValueFormater interface, then you use the method stringForValue to customize the new values, it takes two parameters, the first is the actual value (you can see it like the index) and second is the axis where the value is.

import UIKit
import Foundation
import Charts

@objc(BarChartFormatter)
public class BarChartFormatter: NSObject, IAxisValueFormatter
{
var months: [String]! = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

public func stringForValue(value: Double, axis: AxisBase?) -> String
{
return months[Int(value)]
}
}

Now in your file at the begining of your setChart() function you have to create two variables one for your formatter class and one for the axis class:

let formato:BarChartFormatter = BarChartFormatter()
let xaxis:XAxis = XAxis()

Next, go ahead at the end of the for in loop and pass the index and axis to your formatter variable:

formato.stringForValue(Double(i), axis: xaxis)

After looping add the format to your axis variable:

xaxis.valueFormatter = formato

The final step is to add the new xaxisformatted to the barChartView:

barChartView.xAxis.valueFormatter = xaxis.valueFormatter

And that's all the other lines in the setChart() function just keep it where they are, I hope it can help you.

Using both String and Date on axis charts ios

I've asked one more question here: https://stackoverflow.com/a/62038981/11219710

It turned out, I needed to use this code in my XAxisValueFormatter:

if let index = axis?.entries.firstIndex(of: value), let count = axis?.entries.count  , index == count - 2 {
return "Now"
}

It takes the index before the last one and returns a String type.

How to set a custom x axis 0 label in charts ios

This is a snippet that helps me convert an X axis into timeline and also make the last label on the chart of a String type.

index == count - 2 was used because the label count on X axis was set to 3 by force:

chart.xAxis.setLabelCount(3, force: true)
chart.xAxis.avoidFirstLastClippingEnabled = false
chart.xAxis.forceLabelsEnabled = true
class ChartXAxisFormatter: NSObject, IAxisValueFormatter {

func stringForValue(_ value: Double, axis: AxisBase?) -> String {

if let index = axis?.entries.firstIndex(of: value), let count = axis?.entries.count , index == count - 2 {
return "Now"
}

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm:ss"

let date = Date(timeIntervalSince1970: value)
let time = dateFormatterPrint.string(from: date)

return time
}
}

How to set String value as x of ChartDataEntry.init in Charts?

You can implement delegate method like this

extension LineChartSwiftUI: IAxisValueFormatter {

func stringForValue(_ value: Double, axis: AxisBase?) -> String {
if axis is XAxis {
// do something you need for X axis
return valueTransformedToString
}
}

}

And set value formatter as axis to self as delegated, like this:

lineChart.xAxis.valueFormatter = self

In delegated method you just need to implement values transforming to your format.

How to display a custom text instead of value on X-Axis in Charts

You have to create a class which implements AxisValueFormatter protocol.

The only function you have to implement is func stringForValue(_ value: Double, axis: AxisBase?) -> String

  class SomeClass: AxisValueFormatter  {

func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return weeks[Int(value)]
}
}

var weeks = ["WEEK1", "WEEK2", "WEEK3", "WEEK4"]

chart.xAxis.valueFormatter = SomeClass()

How to add Strings on Left Axis in iOS-charts?

IndexAxisValueFormatter is used for passing an array of x-axis labels, not y-axes labels. You need to create your own y-axis values formatter by implementing IAxisValueFormatter protocol.

E.g, I want to display custom string labels for some values on my y-Axis. I have created MyLeftAxisFormatter class.

class MyLeftAxisFormatter: NSObject, IAxisValueFormatter {

var labels: [Int : String] = [ 0 : "zero", 3 : "three", 6 : "six", 9 : "nine", 12 : "twelve", 15 : "fifteen", 18 : "eighteen"]

func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return labels[Int((value).rounded())] ?? ""
}
}

And use it for left axis on my chart.

lineChartView.leftAxis.valueFormatter = MyLeftAxisFormatter()

Y-Axis Labels

Keep in your mind, that displayed values for y-axis are calculated by charts engine in depending on various factors such as view's height, min/max values, etc. And this values can change when you will change source data.

How to set Strings alongwith Y-axis numbers in ios charts swift

@MichaelV suggested a good start for you. Just use custom value formatter for YAxis as you used it for XAxis. In fact, XAxis and YAxis classes have the same ancestor.

So you need to declare a value formatter class:

class YAxisValueFormatter: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return String(value) + " min"
}
}

And then set this formatter for left and right axes in your chart:

myChart.leftAxis.valueFormatter = YAxisValueFormatter()
myChart.rightAxis.valueFormatter = YAxisValueFormatter()

How to add string labels( xAxis labels) to horizontal bar in Charts framework

Charts framework is a great tool for drawing charts. You should study it perfectly. I used an old code in our project (copy/paste), so it caused some problems for drawing xAxis labels in my chart.

Just comment below line:

    horizontalBarChartView.xAxis.drawLabelsEnabled = false

Custom xAxis formatting in iOS Charts library

You need to update your existing code as below.

  1. Update your data binding for XAxis:
let chartFormatter = LineChartFormatter(labels: xValues)
let xAxis = XAxis()
xAxis.valueFormatter = chartFormatter
self.xAxis.valueFormatter = xAxis.valueFormatter

  1. Update Value Formatter code:

    private class LineChartFormatter: NSObject, IAxisValueFormatter {

    var labels: [String] = []
    let dateFormatter = DateFormatter()
    let dateShortFormatter = DateFormatter()

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {


    if let date = dateFormatter.date(from:labels[Int(value)]) {
    if value == 0 {
    dateShortFormatter.dateFormat = "MMM dd"
    return dateShortFormatter.string(from: date)
    } else {

    let prevDate = dateFormatter.date(from:labels[Int(value - 1)])
    dateShortFormatter.dateFormat = "MMM"
    if dateShortFormatter.string(from: date) != dateShortFormatter.string(from: prevDate!) {
    dateShortFormatter.dateFormat = "MMM dd"
    return dateShortFormatter.string(from: date)
    } else {
    dateShortFormatter.dateFormat = "dd"
    return dateShortFormatter.string(from: date)
    }
    }
    } else {
    return labels[Int(value)]
    }
    }

    init(labels: [String]) {
    super.init()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
    self.labels = labels
    }}

By Above code change, you will achieve your Date formatting in XAxis.



Related Topics



Leave a reply



Submit