Show integer values instead of decimal in MPAndroidChart by PhilJay? - android

I'm using MPAndroidChart for showing hours of work by day.
Everything is working fine, but I can't figure out how to show integer, not float. For example, if I insert 19 hours in chart, it's showing like this at the top of each chart. Can I show it like 19 h?

Set value formatter, If you set 0 in DefaultValueFormatter it will be shown like integer value example 25, if you set 1 now the output will be 25.0
val barDataSet = BarDataSet(entries, "")
barDataSet.valueFormatter = DefaultValueFormatter(0)

Set value Formatter
val xAxis = barChart.xAxis
xAxis.valueFormatter = IAxisValueFormatter { value, axis -> value.roundToInt() }

Related

How to add decimal values to entries for chart using MpAndroidChart Library?

I'm trying to create a line chart in Android using MPAndroidChart Library and as entries I have values like 1200.10, 1300.70 and so on, but on my chart the values are rounded (1200, 1301), and I want to display the original values. How can I do that? I tried different solutions but couldn't solve the problem yet. I'm using the Kotlin language. Thanks!
for (item in reversedCashList) {
if (i <= daysNmb) {
var cashValue: String = transformDataForChart(item.value!!)
dataValsEntries.add(Entry(i, cashValue.toFloat()))
i++
}
}
Also, I'm using this formatter Class to format my values because the initial format is like 120.200,10 and I changed them to 120200.10 but this values is displayed as 120200. My Formatter Class:
private fun transformDataForChart(totalValue: String): String {
return if (totalValue.contains(".")) {
val test = totalValue.replace(".", "")
test.replace(",", ".")
} else {
totalValue.replace(",", ".")
}
}
You can try with BigDecimal, something like BigDecimal.valueOf(X).setScale(decimalPlace(usually 2), BigDecimal.ROUND_HALF_UP).floatValue()
The idea is that float cannot hold so many values as the Double, I've encountered this issue as some point as well, and I had to change everything to Double just to make it more easier to maintain... Therefor I don't think is a straight-forward method to keep everything you need in the float format.

Anychart Android polar plot xAxis labels change them to char strings

Good morning,
I was trying to implement an AnyChart polar plot in android (https://github.com/AnyChart/AnyChart-Android) which should look something similar to this (https://playground.anychart.com/gallery/Polar_Charts/Line_Polar_Chart). I know this example is in javascript and I am developping it within Android, which is not exactly the same, but to keep a reference of the result I want to achieve is fine.
From that example, I have been struggling to change the xAxis Labels (0°, 30°, ...) to custom made strings, such as ("Zero", "Thirty",...).
I didn't manage to find a xAxis label getter which returns the label string (https://api.anychart.com/v8/anychart.core.ui.LabelsFactory#getLabel) but haven't been able to find a label setter...
My aim would be to keep the numerical functionallity of a Anychart polar plot, where a line could be plotted from (45°, value 1) to (45°, value 5) and having displayed chars at the xlabel of the plot, so instead of seeing "45°" to the label, it should say "fourty-five"
Do anyone have any idea if this is achievable?
Thank you very much!
You can achieve that using format() function of the xAxis labels. In the callback function you can implement your own logic on how to translate numbers to words (if, case, hashmap, etc). The snippet describes how to achieve that.
AnyChartView anyChartView = findViewById(R.id.any_chart_view);
Polar polar = AnyChart.polar();
List<DataEntry> data = new ArrayList<>();
data.add(new ValueDataEntry(0, 10));
data.add(new ValueDataEntry(15, 8));
data.add(new ValueDataEntry(30, 12));
data.add(new ValueDataEntry(45, 11));
Set set = Set.instantiate();
set.data(data);
Mapping series1Data = set.mapAs("{ x: 'x', value: 'value' }");
polar.line(series1Data);
Linear scale = Linear.instantiate();
scale.minimum(0).maximum(360);
scale.ticks().interval(30);
polar.xScale(scale);
polar.xAxis().labels().format("function() {" +
"if (this.tickValue == 60) return 'sixty';" +
"if (this.tickValue == 90) return 'ninety';" +
"if (this.tickValue == 120) return 'hundred twenty';" +
"return this.tickValue;" +
"}");
anyChartView.setChart(polar);
Below is the result:

Updating Column chart dynamically throws UnsupportedOperationException

We have a Donut chart and when a slice is clicked on the donut chart we would like to update the values in the ColumnChart.
This is how we set the listener for donut chart
segments.forEach(Consumer { segment: PieSegment ->
segment.addIsSelectedChangeListener {
drawColumnChart(clickedSliceProperties)
}
})
The method which draws the ColumnChart
private fun drawColumnChart(values: Array<Int>) {
val xAxis: IAxis = sciChartBuilder.newNumericAxis().withGrowBy(0.15, 0.15).withLabelProvider(YearsLabelProvider()).build()
val yAxis: IAxis = sciChartBuilder.newNumericAxis().withGrowBy(0.0, 0.0).build()
xAxis.autoRange = AutoRange.Always
yAxis.autoRange = AutoRange.Always
val dataSeries: IXyDataSeries<Int, Int> = sciChartBuilder.newXyDataSeries(Int::class.javaObjectType, Int::class.javaObjectType).build()
for (i in values.indices) {
dataSeries.append(i, values[i])
}
val rSeries = sciChartBuilder.newColumnSeries()
.withStrokeStyle(-0xdcdcdd, 0.4f)
.withDataPointWidth(0.5)
.withDataSeries(dataSeries)
.withPaletteProvider(ColumnsPaletteProvider())
.build()
UpdateSuspender.using(lineChart) {
lineChart.theme = R.style.SciChart_Bright_Spark
Collections.addAll(lineChart.xAxes, xAxis)
Collections.addAll(lineChart.yAxes, yAxis)
Collections.addAll(lineChart.renderableSeries, rSeries)
Collections.addAll(lineChart.chartModifiers, sciChartBuilder.newModifierGroupWithDefaultModifiers().build())
sciChartBuilder.newAnimator(rSeries).withWaveTransformation().withInterpolator(DecelerateInterpolator()).withDuration(3000).withStartDelay(350).start()
}
}
Trying to pass a different set of values to drawColumnChart() method this exception is thrown.
java.lang.UnsupportedOperationException: AxisCollection.getAxisById('DefaultAxisId') returned more than one axis with the ID=DefaultAxisId. Please check you have assigned correct axis Ids when you have multiple axes in SciChart
Thanks for your time :)
This exception is thrown, because each axis in xAxes/yAxes collection should have unique id. Also you should have in mind that in case of multiple axes you also need to assign correct axis id for renderable series. Please take a look on SciChart tutorial that how to add multiple axes into the chart..
So in your case code for creation of axes should look like this:
val xAxis: IAxis = sciChartBuilder.newNumericAxis().withAxisId(uniqueXAxisId).withGrowBy(0.15, 0.15).withLabelProvider(YearsLabelProvider()).build()
val yAxis: IAxis = sciChartBuilder.newNumericAxis().withAxisId(uniqueYAxisId).withGrowBy(0.0, 0.0).build()
and code for creation of renderable series like this:
val rSeries = sciChartBuilder.newColumnSeries()
.withXAxisId(uniqueXAxisId)
.withYAxisId(uniqueYAxisId)
.withStrokeStyle(-0xdcdcdd, 0.4f)
.withDataPointWidth(0.5)
.withDataSeries(dataSeries)
.withPaletteProvider(ColumnsPaletteProvider())
.build()
However if you want to update column values without adding new series, then just create and set xAxis, yAxis and renderable series once outside listener, store data series in private field and in listener update data series with new data instead of recreating it every time:
dataSeries.clear()
for (i in values.indices) {
dataSeries.append(i, values[i])
}

Kotlin: SumbyDouble returning additional decimals

I am summing double value from arraylist its giving additional decimals as 99999, how to fix this, please guide
ex
class ExDet{var expName:String ="",var expAmount:Double = 0.0}
val arrayList = ArrayList<ExDet>()
arrayList.add(ExDet("Abc 1",45.66))
arrayList.add(ExDet("DEF 1",10.0))
arrayList.add(ExDet("Lee 1",600.89))
arrayList.add(ExDet("Ifr 1",200.9))
var amt = arrayList.sumByDouble{ it.expAmount }
Expected Value of Amount is :
Amt = 857.45
But it returns
Amt = 857.4499999
Sample Code to Test
data class ExDet(var expName:String ="" ,var expAmount:Double=0.0)
fun main(args: Array<String>) {
val arrayList = ArrayList<ExDet>()
arrayList.add(ExDet("Abc 1",45.66))
arrayList.add(ExDet("DEF 1",10.0))
arrayList.add(ExDet("Lee 1",600.89))
arrayList.add(ExDet("Ifr 1",200.9))
var amt = arrayList.sumByDouble{ it.expAmount }
println("Amount is : $amt")
}
The issue you are confronted with is that floating point numbers are build on top of base 2, not base 10.
Think how you can easily represent a third as a fraction (1/3), but when you convert to decimal you get a repeating (recurring) number after the radix point (i.e. 0.33...). Some decimal numbers are recurring when represented in base-2, e.g. x.9. The computer has a finite number of bits, so the (base-2) number is truncated. All the truncation errors can add up.
You need to round to the required precision (e.g. round(x * 100) / 100).
If you are only interested in how it is displayed then you can use the format function with something like "%.2f".
String.format("%.2f", value)

How to Change the X-axis using Graph View Demo in android

Basically i want to draw a graph where x-axis gives you the date and y axis gives u the count
I am getting data from server and parsing it in my two array's one is for count and other is for date
i am getting values in two array like this
SoapObject o=(SoapObject)p2.getProperty(xx);
UserCallStatusBean ld=new UserCallStatusBean();
if(o.getProperty("Month").toString().equals("anyType{}")){
ld.setDuration("");
}
else{
ld.setDuration(o.getProperty("Month").toString());
}
ld.setCount(Integer.parseInt(o.getProperty("Count").toString()));
CallStatus.add(ld);
GraphViewData o1=new GraphViewData(_iLoopCounter,Double.parseDouble(o.getProperty("Count").toString()));
String o2=new String(o.getProperty("Month").toString());
//String o2=new String(String.valueOf(_iLoopCounter));
arrData[xx]=o1;
arrXaxis[xx]=o2;
_iLoopCounter++;
After Getting the Value in two array i use Graph View Demo to create a grapg like
setContentView(R.layout.graphs);
// init example series data
exampleSeries = new GraphViewSeries(arrData);
// graph with dynamically genereated horizontal and vertical labels
GraphView graphView;
graphView = new BarGraphView(
this,"");
graphView.addSeries(exampleSeries); // data
graphView.setScalable(true);
graphView.setScrollable(true);
graphView.setViewPort(2,6);
graphView.setScrollable(true);
graphView.setHorizontalLabels(arrXaxis);
graphView.setGravity(Gravity.CENTER);
graphView.setBaselineAlignedChildIndex(4);
//graphView.setHorizontalLabels(labels);
LinearLayout layout = (LinearLayout) findViewById(R.id.graph1);
layout.addView(graphView);
Now My issue of concern is i am getting value of count on y-axis but i am also getting count of date on x-axis instead i want to show the date on x-axis
I Have read various articles to get string value on x-axis ,finded one to use Cutom lavel formatter , But didnt knw how to use so what i can do to get x-axis ? (Date Value)
I hope u understands ,Expecting Answer Pleasue will b aLl Mine
Thanks in advance

Categories

Resources