I need to create a line graph where each point represents a product purchased and where the x axis represents the hours of the day (from 0 to 24), while the y represents the cost of that product. For each object I add I go to Recompose the Composable but even though I create the point with the right coordinates, the points do not show where they should.
@Composable
fun StaticLineChart(pointsData: List<Point>) {
if(pointsData.isNotEmpty()) {
SingleLineChartWithGridLines(pointsData)
} else {
Box(
modifier = Modifier
.fillMaxWidth()
.height(300.dp),
contentAlignment = Alignment.Center
) {
Text(
text = "No orders today",
style = MaterialTheme.typography.bodyMedium,
color = Color.Gray
)
}
}
}
@Composable
private fun SingleLineChartWithGridLines(pointsData: List<Point>) {
val steps = 8
val xMax= 24f
val yMin= 0f
val yMax = pointsData.maxOfOrNull { it.y }?.takeIf { it > 300f } ?: 300f
pointsData.forEach { point ->
println("Rendering Point: x=${point.x}, y=${point.y}")
}
// Impostare l'asse X con etichette per 24 ore in modo che siano visibili da 0 a 24
val xAxisData = AxisData.Builder()
.axisStepSize(30.dp)
.topPadding(105.dp)
.steps(steps) // 24 ore
.labelData { i -> ((i * (xMax / steps))).toInt().toString() } // Mostra etichette ogni 3 ore: 0, 3, 6, ..., 24
.labelAndAxisLinePadding(15.dp)
.build()
// Impostare l'asse Y con un minimo fisso di 0 e massimo di almeno 300
val yAxisData = AxisData.Builder()
.steps(steps)
.labelAndAxisLinePadding(20.dp)
.labelData { i ->
val yScale = (yMax - yMin) / steps
((i * yScale) + yMin).formatToSinglePrecision()
}
.build()
val data = LineChartData(
linePlotData = LinePlotData(
lines = listOf(
Line(
dataPoints = pointsData,
lineStyle = LineStyle(width = 2f),
intersectionPoint = IntersectionPoint(radius = 3.dp),
selectionHighlightPoint = SelectionHighlightPoint(radius = 1.dp),
shadowUnderLine = ShadowUnderLine(),
selectionHighlightPopUp = SelectionHighlightPopUp()
)
)
),
xAxisData = xAxisData,
yAxisData = yAxisData,
)
LineChart(
modifier = Modifier
.fillMaxWidth()
.height(300.dp),
lineChartData = data
)
}
An example of point in the chart
Could someone with experience in this matter help me?
New contributor
Francesco Gallo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.