I try to manage text in PieChart of MPAndroidChart. But when my text is difficult situation like True = 2, False = 3 , Not = 95, in this situation my pie chart layout is very bad.
Here is my code :-
fun setupPieChartView() {
mPie = findViewById(R.id.piechart)
mPie?.setUsePercentValues(true)
val desc: Description = Description()
desc.text = "PieChart"
mPie?.description = desc
val legend: Legend? = mPie?.legend
legend?.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
val value = Arrays.asList(trueAns.toFloat(), wrongAns.toFloat(), noAns.toFloat())
val label = Arrays.asList("True", "false", "Not")
val entry = ArrayList<PieEntry>()
for (i in value.indices) {
entry.add(PieEntry(value.get(i), label.get(i)))
}
val dataSet = PieDataSet(entry, "Result")
dataSet.setColors(Color.GREEN, Color.RED, Color.GRAY);
dataSet.setDrawValues(true)
val pieData = PieData(dataSet)
pieData.setValueFormatter(PercentFormatter())
pieData.setValueTextSize(10f)
pieData.setValueTextColor(Color.WHITE)
mPie?.data = pieData
}
Result is like that :-
here in my Pie-Chart data is not set in good format . Help me for this
You need this line, so your labels will be outside graph:
dataSet.setYValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
And value will be outside . You can also control position, line length and coloring like this:
pieData.setValueTextColor(Color.BLACK);
dataSet.setValueLinePart1OffsetPercentage(10.f);
dataSet.setValueLinePart1Length(0.43f);
dataSet.setValueLinePart2Length(.1f);
dataSet.setValueTextColor(Color.BLACK);
dataSet.setXValuePosition(PieDataSet.ValuePosition.OUTSIDE_SLICE);
mPie.setEntryLabelColor(Color.BLUE);
Here is result:
Related
// Create new 6 Pot
val list = mutableListOf<Int>()
val pot = listOf<Pot>(Pot(50), Pot(50), Pot(50), Pot(50), Pot(50), Pot(50))
val linearLayout: LinearLayout = findViewById(R.id.text)
linearLayout.removeAllViews()
// random 6 number from 1 - 50 without duplicate
// Create textview to print out roll result
pot.forEach {
val d = it
val rollResult = d.roll()
list.add(rollResult)
val textView = TextView(this)
textView.append(this.toString())
val param = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
param.marginStart = 10
textView.layoutParams = param
textView.text = rollResult.toString()
linearLayout.addView(textView)
}
I have a code like this, after add rollResult to a list like a temp paper, what should i do to compare next result to previous result which is in the list, if it already present then do another roll, from start to end. Thanks
You can use distinct(),
Ref : https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/distinct.html
Example
var list = listOf(1,2,4,5,1,6,8,2,4,3,3,5)
list = list.distinct();
println(list)
First loop for generating roll results
pot.forEach {
val d = it
val rollResult = d.roll()
list.add(rollResult)
}
Second Loop for adding dynamic views
list = list.distinct();
list.forEach {
// Add Views etc
}
Modify as per your needs.
Check whether the element is present in the whole list or not try below code :
if(list.contains(element)){ // do rollout again}
My MPAndroidChart displays a stronger line to represent the middle of the graph. How do I avoid that please?
Here is what I have at the moment:
private fun addChart(totals: Totals) {
chart1.apply {
isDragEnabled = true
isScaleXEnabled = false
isScaleYEnabled = true
axisRight.isEnabled = false
axisLeft.setDrawAxisLine(false)
xAxis.isEnabled = false
legend.isEnabled = false
description.text = ""
setTouchEnabled(false)
}
val y: YAxis = chart1.axisLeft
y.axisMaximum = 800f
y.axisMinimum = 0f
y.labelCount = 5
val yValues = ArrayList<Entry>()
for ((index, i) in totals.features!!.withIndex()) {
yValues.add(Entry(index.toFloat(), i.attributes?.confirmedCovidCases!!.toFloat()))
}
val set1 = LineDataSet(yValues, "Data set 1")
set1.color = resources.getColor(R.color.orange)
set1.setDrawCircles(false)
val dataSets = ArrayList<ILineDataSet>()
dataSets.add(set1)
val data = LineData(dataSets)
chart1.data = data
}
Thank you very much.
I try to recreate your chart but did not have the problem
Try to run it on device, because it might your PC/simulator pixel bleeding
I have a problem updating the data in a chart. When I change the settings and come back to this fragment or when I go out of the app and come back, the chart apparently changes its size and hide the labels in its axis. However, if I navigate through the app and come back, the chart is displaying well.
Screenshot of correct display
Screenshot of axis labels disappearing
My context is the following:
I have a fragment where I observe the viewmodel in onViewCreated. When the data is successfully retrieved, I update the chart. I have tried also to make a flag to make sure that the call to set up the chart is only called once, but that doesn't work either. So the problem is not related to how many times this call is made.
viewModel.forecast.observe(viewLifecycleOwner, Observer { resource ->
if (resource != null && resource.status.isSuccessful()){
ChartUtilities.setUpChart(
viewModel.forecastOfNextHours().subList(0, 9),
binding.lineChart,
"Temperature of the next 24 hours",
isMetric
)
}
In ChartUtilities.kt:
object ChartUtilities {
fun setUpChart(list: List<ForecastListItem>, lineChart: LineChart, label: String, isMetric: Boolean){
//lineChart.clear()
val (values, yValues, xAxisValues) = fillData(list, isMetric)
val data = configureDataSet(values, label)
customSettings(lineChart, data, xAxisValues, yValues)
//lineChart.notifyDataSetChanged()
}
private fun configureDataSet(
values: ArrayList<Entry>,
label: String
): LineData {
val set1 = LineDataSet(values, label)
set1.axisDependency = YAxis.AxisDependency.LEFT
set1.color = ColorTemplate.getHoloBlue()
set1.valueTextColor = ColorTemplate.getHoloBlue()
set1.lineWidth = 4.0f
set1.setDrawCircles(false)
set1.setDrawValues(false)
set1.fillAlpha = 65
set1.fillColor = Color.RED
set1.highLightColor = Color.rgb(244, 117, 117)
set1.setDrawCircleHole(false)
set1.mode = LineDataSet.Mode.HORIZONTAL_BEZIER
// create a data object with the data sets
val data = LineData(set1)
data.setValueTextColor(Color.WHITE)
data.setValueTextSize(9f)
return data
}
private fun fillData(list: List<ForecastListItem>, isMetric: Boolean): Triple<ArrayList<Entry>, ArrayList<Double>, ArrayList<String>> {
val values = ArrayList<Entry>()
val yValues = ArrayList<Double>()
val xAxisValues = arrayListOf<String>()
list.forEachIndexed { index, forecastItem ->
xAxisValues.add(forecastItem.getHourOfDay())
var temperature = forecastItem.getTemperature()!!
if (!isMetric)
temperature = WeatherUtils.celsiusToFahrenheit(temperature)
yValues.add(temperature)
values.add(Entry(index.toFloat(), temperature.toFloat()))
}
return Triple(values, yValues, xAxisValues)
}
private fun customSettings(chart: LineChart, data: LineData, xAxisValues: ArrayList<String>, yAxisValues: ArrayList<Double>){
chart.data = data
customChart(chart)
customLegend(chart)
customXAxis(chart, xAxisValues)
customYAxis(chart, yAxisValues)
val rightAxis = chart.axisRight
rightAxis.isEnabled = false
}
private fun customChart(chart: LineChart) {
chart.description.isEnabled = false
chart.setTouchEnabled(false)
//chart.dragDecelerationFrictionCoef = 0.9f
// enable scaling and dragging
chart.isDragEnabled = false
chart.setScaleEnabled(false)
chart.setDrawGridBackground(false)
chart.isHighlightPerDragEnabled = true
// set an alternative background color
chart.setBackgroundResource(R.color.colorPrimaryDark)
chart.setViewPortOffsets(0f, 0f, 0f, 0f)
}
private fun customLegend(chart: LineChart) {
val l = chart.legend
l.isEnabled = true
l.verticalAlignment = Legend.LegendVerticalAlignment.TOP
l.textColor = Color.WHITE
}
private fun customXAxis(
chart: LineChart,
xAxisValues: ArrayList<String>
) {
val xAxis = chart.xAxis
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.textSize = 12f
xAxis.setDrawAxisLine(true)
xAxis.setDrawGridLines(false)
xAxis.textColor = Color.WHITE
//xAxis.setCenterAxisLabels(true)
xAxis.setAvoidFirstLastClipping(false)
xAxis.granularity = 2f // three hours
xAxis.axisMaximum = xAxisValues.size.toFloat()
xAxis.labelCount = xAxisValues.size
xAxis.valueFormatter = IndexAxisValueFormatter(xAxisValues)
xAxis.isEnabled = true
}
private fun customYAxis(
chart: LineChart,
yAxisValues: ArrayList<Double>
) {
val leftAxis = chart.axisLeft
leftAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
leftAxis.textColor = Color.WHITE
leftAxis.setDrawGridLines(true)
leftAxis.isGranularityEnabled = true
leftAxis.axisMinimum = yAxisValues.min()?.minus(10)?.toFloat()!!
leftAxis.axisMaximum = yAxisValues.max()?.plus(10)?.toFloat()!!
leftAxis.yOffset = -9f
leftAxis.isEnabled = true
}
}
I realise this is a very late answer, but I had exactly the same issue and stumbled upon your question. I'd intermittently see the axes disappear when scrolling between different charts (I had them in a RecyclerView).
I solved it by deleting the following line, which I see you also have in your code:
chart.setViewPortOffsets(0, 0, 0, 0);
The javadoc for that method says that we should avoid manually setting it unless we know what we're doing (which I don't!).
I also found that increasing the values to the following worked for me:
chart.setViewPortOffsets(60, 0, 50, 60);
I have a MPChart and I am setting the values like this
lineChart.legend.isEnabled = false
lineChart.description.isEnabled = false
val entryList = arrayListOf<Entry>()
val sortedList = stockGraphResponse?.prices?.sortedWith(compareBy {
it?.date
})
for (i in 0 until sortedList?.size!!) {
val item = Utils.replaceCommaInNumber(sortedList[i]?.price!!).toFloat()
entryList.add(Entry(sortedList[i]?.date?.toFloat()!!, item))
}
val lineDataSet = LineDataSet(entryList,"")
lineDataSet.setDrawCircles(false)
lineDataSet.setDrawFilled(true)
val lineData = LineData(lineDataSet)
lineChart.data = lineData
lineChart.setDrawBorders(true)
val xAxis = lineChart.xAxis
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.setValueFormatter(CustomFormatter())
xAxis.setLabelCount(5,true)
val yAxis = lineChart.axisLeft
val yRight = lineChart.axisRight
yRight.isEnabled = false
lineChart.isAutoScaleMinMaxEnabled = true
lineChart.invalidate()
And the result is this graph
I am setting 5 for label count in xAxis and I am getting 5 labels but then the values are being plotted like that and so they are overlapping. I tried using granularity but still the same. How can I streamline this? Any help would be appreciated. Thanks
I try to set color in PieChart of MPAndroidChart.But its not set it.I want to add custom color in my partition . Here is my code :-
fun setupPieChartView() {
mPie = findViewById(R.id.piechart)
mPie?.setUsePercentValues(true)
val desc: Description = Description()
desc.text = "PieChart"
mPie?.description = desc
val legend: Legend? = mPie?.legend
legend?.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT
val value = Arrays.asList(trueAns.toFloat(), wrongAns.toFloat(), noAns.toFloat())
val label = Arrays.asList("True", "false", "Not")
val entry = ArrayList<PieEntry>()
for (i in value.indices) {
entry.add(PieEntry(value.get(i), label.get(i)))
}
val dataSet = PieDataSet(entry, "Result")
dataSet.setDrawValues(true)
val pieData = PieData(dataSet)
pieData.setValueFormatter(PercentFormatter())
pieData.setValueTextSize(10f)
pieData.setValueTextColor(Color.WHITE)
mPie?.data = pieData
}
Instead of this
dataSet.colors = ColorTemplate.COLORFUL_COLORS.toList()
it should be
dataSet.setColors(Color.RED, Color.GREEN, Color.BLUE);
Because first one gives default colors, that's why you can't override colors. Here is result of your code :