Open1

Jetpack ComposeでMPAndroidChartを使う

gari8gari8

レーダーチャートはこんな感じで描画できる

RadarGraph.kt
package com.example.XXX

import android.graphics.Color
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.width
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import com.github.mikephil.charting.charts.RadarChart
import com.github.mikephil.charting.data.RadarData
import com.github.mikephil.charting.data.RadarDataSet
import com.github.mikephil.charting.data.RadarEntry
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter


@Composable
fun RadarGraph(resultMap: Map<String, Float>) {
    AndroidView(
        factory = { context ->
            val radarChart = RadarChart(context)
            val entries = mutableListOf<RadarEntry>()
            val labels = mutableListOf<String>()
            for ((k, v) in resultMap) {
                entries.add(RadarEntry(v, k))
                labels.add(k)
            }
            val dataSet = RadarDataSet(entries, "").apply {
                color = Color.RED
            }

            val xAxis = radarChart.xAxis
            xAxis.valueFormatter = IndexAxisValueFormatter(
                labels
            )
            val l = radarChart.legend
            l.isEnabled = false

            val desc = radarChart.description
            desc.isEnabled = false
            val radarData = RadarData(dataSet)
            radarChart.data = radarData
            radarChart.invalidate()
            radarChart
        },
        modifier = Modifier
            .height(300.dp)
            .width(400.dp),
    )
}

呼び出しはこんな感じ?

MainActivity.kt
...
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            RadarGraph(resultMap = resultMap)
        }
    }
}
...