0

I am integrating the ios-charts. I want to layout the y-axis of graph dynamically on the basis of json response. For example:- if json contains 50 values, then I will draw 10(50/5)+5 = 15 yaxis values. These 15 values must contains the minimum and maximum json value. the remaining 13 values must have fixed-step between them. I write multiple logic and fail to deliver the right results. I am open to ideas.

pkc456
  • 8,350
  • 38
  • 53
  • 109

1 Answers1

1

You need to find the least common multiple and use this as a basis to pick out the right values. I found some nice work here: Ray Wenderlich Algorithms

In your above example you will wind up with a commonMultiple = 150. originalCount is the number of values you had to begin with (50).

Then it would be something like this I guess. values is an array of values created from your json.

var multipliedValues = [Int]()
for value in values {
    multipliedValues += [Int](repeating: value, count: commonMultiple/originalCount)
}

Then you are ready to pick out a subset of values:

let numberOfSteps = (originalCount/5)+5
var yValues = [Int]()
for n in 0..<numberOfSteps{
    let index = n*commonMultiple/numberOfSteps
    yValues.append(multipliedValues[index])
}

Then the final tricky part is to insert the lowest and highest values. Something like this perhaps:

let minValue = values.sorted().first!
if !yValues.contains(minValue) {
    let minIndex = multipliedValues.index(of: minValue)! / (commonMultiple/numberOfSteps)
    yValues[minIndex] = minValue
}
let maxValue = values.sorted().last!
if !yValues.contains(maxValue) {
    let maxIndex = multipliedValues.index(of: maxValue)! / (commonMultiple/numberOfSteps)
    yValues[maxIndex] = maxValue
}
T. Benjamin Larsen
  • 6,373
  • 4
  • 22
  • 32