Skip to content

Instantly share code, notes, and snippets.

@nyamwaya
Last active June 9, 2019 17:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nyamwaya/20256960ce4a34e42fba7f3dc9507d4d to your computer and use it in GitHub Desktop.
Save nyamwaya/20256960ce4a34e42fba7f3dc9507d4d to your computer and use it in GitHub Desktop.
Android Histogram using GraphView in Kotlin
//This method takes as parameters the bincount; which is the number of bins you want your histogram to have
//and your data in the form of a double array.
//Based on this SO answer "https://stackoverflow.com/questions/10786465/how-to-generate-bins-for-histogram-using-apache-math-3-0-in-java"
private fun displayHistogram(binCount: Int, data: DoubleArray) {
val histogram = DoubleArray(binCount)
val distribution = org.apache.commons.math3.random.EmpiricalDistribution(binCount)
distribution.load(data)
//Not sure what this variable K does to be honest.
var k = 0
for (stats in distribution.binStats) {
histogram[k++] = stats.n.toDouble()
}
//binSize is the length of the bin. For example a bin size could span from 1-5
//We need to know this in order to calculate the x values of the histogram
val binSize = (data.max()!!.toDouble() - data.min()!!.toDouble()) / binCount
//The size of the histogram is the number of bins and the value of histogram[] at i index is the frequency of numbers
//within the interval represented by binSize.
//So for example, histogram[] at index 1 has a frequcny or value of 2 for the range or binsize of between 1-5 occured 4
for (i in 0 until histogram.size) {
series2?.appendData(DataPoint(
//x values
generateHistogramXValues(data.min()!!.toDouble(), histogram.size, binSize)[i],
//y values are the frequnecy of numbers within our binsize
histogram[i]
), false, histogram.count())
}
}
//Simply creates an x values double array that gives the x axis positin for each bin
private fun generateHistogramXValues(min: Double, numberOfBIns: Int, binSize: Double): DoubleArray {
//create new array
val xValuesArray = DoubleArray(numberOfBIns)
//loop from zero to the number of bins you desier. so if 5 bins then 5
for (i in 0 until numberOfBIns) {
//the first item in the array needs to be the first bin which is also the min of our data
if (i == 0){
//set initial value to the min of our data if array is empty
xValuesArray[i] = min
}else{
//add to the previous value in the array by a specific interval which is our binsize
val previous = xValuesArray[i-1]
xValuesArray[i] = previous+binSize
}
}
return xValuesArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment