@Composable fun ExpensesGraph(paddingValues: PaddingValues) { val db =…
- User
@Composable fun ExpensesGraph(paddingValues: PaddingValues) { val db = FirebaseFirestore.getInstance()
// Define your timeframes val timeFrames = listOf("Daily", "Weekly", "Monthly", "Yearly") val selectedIndex = remember { mutableStateOf(0) } // Fetch and process the expenses data val chartEntries = remember { mutableStateOf(entriesOf(*arrayOf<Float>())) } val chartModelProducer = ChartEntryModelProducer(chartEntries.value) val markers = remember { mutableStateOf<Map<Float, Marker>>(emptyMap()) } fun fetchExpensesData(timeFrame: String) { val startCalendar = Calendar.getInstance() val endCalendar = Calendar.getInstance() var dateFormat: SimpleDateFormat when (timeFrame) { "Daily" -> { // Daily: Showing 7 days in a week startCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set(Calendar.DAY_OF_WEEK, startCalendar.firstDayOfWeek + 1) endCalendar.add(Calendar.DATE, 6) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault()) } "Weekly" -> { // Weekly: Showing 4 weeks in a month startCalendar.set(Calendar.DAY_OF_MONTH, 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set( Calendar.DAY_OF_MONTH, startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH), ) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault()) } "Monthly" -> { // Monthly: Showing 12 months in a year startCalendar.set(Calendar.MONTH, 0) startCalendar.set(Calendar.DAY_OF_MONTH, 1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set(Calendar.MONTH, 11) endCalendar.set( Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) ) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("MMM_yyyy", Locale.getDefault()) } "Yearly" -> { startCalendar.set(Calendar.MONTH, 0) startCalendar.set(Calendar.DAY_OF_MONTH, -1) startCalendar.set(Calendar.HOUR_OF_DAY, 0) startCalendar.set(Calendar.MINUTE, 0) startCalendar.set(Calendar.SECOND, 0) startCalendar.set(Calendar.MILLISECOND, 0) endCalendar.set(Calendar.MONTH, 11) endCalendar.set(Calendar.DAY_OF_MONTH, 31) endCalendar.set(Calendar.HOUR_OF_DAY, 0) endCalendar.set(Calendar.MINUTE, 0) endCalendar.set(Calendar.SECOND, 0) endCalendar.set(Calendar.MILLISECOND, 0) dateFormat = SimpleDateFormat("yyyy", Locale.getDefault()) } else -> { throw IllegalArgumentException("Unsupported time frame: $timeFrame") } } val query = db.collection("expenses") .document("Kantin") .collection(timeFrame.lowercase()) query.get().addOnSuccessListener { result -> val expenses = mutableListOf<Pair<Float, Date>>() for (document in result) { val total = document.getDouble("total")?.toFloat() ?: 0f val date = dateFormat.parse(document.id) ?: Date() expenses.add(total to date) println("Document: ${document.id}, Total: $total, Date: $date") } println(startCalendar.time) println(endCalendar.time) expenses.retainAll { it.second >= startCalendar.time && it.second <= endCalendar.time } // Sort the expenses by date expenses.sortBy { it.second } chartEntries.value = entriesOf(*expenses.mapIndexed { index, expense -> index.toFloat() to expense.first } .toTypedArray()) } } LaunchedEffect(Unit) { fetchExpensesData(timeFrames[selectedIndex.value]) } Column(modifier = Modifier.padding(paddingValues)) { timeFrames.forEachIndexed { index, timeFrame -> Button( onClick = { selectedIndex.value = index fetchExpensesData(timeFrame) }, colors = ButtonDefaults.buttonColors( containerColor = if (selectedIndex.value == index) DarkGray else LightGray ) ) { Text(timeFrame) } } ProvideChartStyle(chartStyle = m3ChartStyle()) { Chart( chart = columnChart(), chartModelProducer = chartModelProducer, startAxis = startAxis(), bottomAxis = bottomAxis(), ) } }}
this is my expenses graph screen, right now the amount of x axis will be dependent to the amount of document in the firestore, I want it to be persistent so for example in my daily timeframe it will always show Monday to Sunday in the x axis even though there is still no data for Wednesday to Sunday
this is the bottomAxis composable from the library
@Composable public fun bottomAxis( label: TextComponent? = axisLabelComponent(), axis: LineComponent? = axisLineComponent(), tick: LineComponent? = axisTickComponent(), tickLength: Dp = currentChartStyle.axis.axisTickLength, tickPosition: HorizontalAxis.TickPosition = HorizontalAxis.TickPosition.Edge, guideline: LineComponent? = axisGuidelineComponent(), valueFormatter: AxisValueFormatter<AxisPosition.Horizontal.Bottom> = DecimalFormatAxisValueFormatter(), sizeConstraint: Axis.SizeConstraint = Axis.SizeConstraint.Auto(), titleComponent: TextComponent? = null, title: CharSequence? = null, labelRotationDegrees: Float = currentChartStyle.axis.axisLabelRotationDegrees, ): HorizontalAxis<AxisPosition.Horizontal.Bottom> = createHorizontalAxis { this.label = label this.axis = axis this.tick = tick this.guideline = guideline this.valueFormatter = valueFormatter this.tickLengthDp = tickLength.value this.tickPosition = tickPosition this.sizeConstraint = sizeConstraint this.labelRotationDegrees = labelRotationDegrees this.titleComponent = titleComponent this.title = title }
- Assistant
To make the X-axis display all days of the week and keep the axis labels consistent, you can modify the
ChartEntryModelProducerto include all days of the week regardless if there is data or not. Here's one way to do it:- Prepare an array of days in a week, something like
val daysOfWeek = arrayOf("Monday", "Tuesday", "Wednesday", …) - For the daily timeframe, create an array of length 7 initialized with 0 values.
- Map the expenses data to the appropriate index in the array based on the day of the week.
Here's an example of how to do this when processing your fetched data:
val startCalendar = Calendar.getInstance() // 1. Prepare an array of days in a week val daysOfWeek = startCalendar.getDisplayName( Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault() ) // ... // process fetched data val expenses = mutableListOf<Pair<Float, Date>>() // ... // 2. Create an array of length 7 initialized with 0 values val dailyExpenses = Array(7){0f} // 3. Map the expenses data to the appropriate index in the array based on the day of the week expenses.forEach { (value, date) -> startCalendar.time = date val dayOfWeek = startCalendar.get(Calendar.DAY_OF_WEEK) val index = (dayOfWeek - startCalendar.firstDayOfWeek + 7) % 7 dailyExpenses[index] = value } chartEntries.value = entriesOf(*dailyExpenses.mapIndexed { index, value -> index.toFloat() to value }.toTypedArray())By doing this, your
chartEntrieswill always contain 7 elements (one for each day of the week), even if there is no data for some days.Then, you should also modify the labels on the X-axis to display the days of the week. Create a custom
AxisValueFormatterfor this purpose:val daysOfWeekFormatter = object : AxisValueFormatter<AxisPosition.Horizontal.Bottom> { override fun format(value: Float, label: Text) = when (value.toInt()) { 0 -> "Monday" 1 -> "Tuesday" 2 -> "Wednesday" 3 -> "Thursday" 4 -> "Friday" 5 -> "Saturday" 6 -> "Sunday" else -> "" } }Lastly, set the valueFormatter for the bottomAxis:
bottomAxis(valueFormatter = daysOfWeekFormatter)This should create a consistent X-axis containing labels for all days of the week, even if there is no data for some days. Note that this is suitable for the daily timeframe only. You can create similar formatters for weekly, monthly, and yearly timeframes as needed.
- Prepare an array of days in a week, something like
- User
please create for all the other timeframes and please provide the full code in your answer
- Assistant
Here's a complete modified
ExpensesGraphcomposable function with all the necessary updates to handle daily, weekly, monthly, and yearly timeframes:@Composable fun ExpensesGraph(paddingValues: PaddingValues) { val db = FirebaseFirestore.getInstance() // Define your timeframes val timeFrames = listOf("Daily", "Weekly", "Monthly", "Yearly") val selectedIndex = remember { mutableStateOf(0) } // Fetch and process the expenses data val chartEntries = remember { mutableStateOf(entriesOf(*arrayOf<Float>())) } val chartModelProducer = ChartEntryModelProducer(chartEntries.value) fun fetchExpensesData(timeFrame: String) { val startCalendar = Calendar.getInstance() val endCalendar = Calendar.getInstance() var dateFormat: SimpleDateFormat when (timeFrame) { "Daily" -> { // Daily: Showing 7 days in a week // ... (Your previous daily code) dateFormat = SimpleDateFormat("EEEE_dd_MMM_yyyy", Locale.getDefault()) } "Weekly" -> { // Weekly: Showing 4 weeks in a month // ... (Your previous weekly code) dateFormat = SimpleDateFormat("W_MMM_yyyy", Locale.getDefault()) } "Monthly" -> { // Monthly: Showing 12 months in a year // ... (Your previous monthly code) dateFormat = SimpleDateFormat("MMM_yyyy", Locale.getDefault()) } "Yearly" -> { // Yearly // ... (Your previous yearly code) dateFormat = SimpleDateFormat("yyyy", Locale.getDefault()) } else -> { throw IllegalArgumentException("Unsupported time frame: $timeFrame") } } // Call query.get().addOnSuccessListener the same as you currently do // ... // After fetching the data, process it based on the selected timeframe: // Each timeframe needs its own X-axis value processor lateinit var xValueProcessor: (List<Pair<Float, Date>>) -> List<Pair<Float, Float>> when (timeFrame) { "Daily" -> { xValueProcessor = { expenses -> val dailyExpenses = Array(7) { 0f } expenses.forEach { (value, date) -> startCalendar.time = date val dayOfWeek = startCalendar.get(Calendar.DAY_OF_WEEK) val index = (dayOfWeek - startCalendar.firstDayOfWeek + 7) % 7 dailyExpenses[index] = value } dailyExpenses.mapIndexed { index, value -> index.toFloat() to value } } } "Weekly" -> { xValueProcessor = { expenses -> val weeklyExpenses = MutableList(4) { 0f } expenses.forEach { (value, date) -> startCalendar.time = date val weekOfMonth = startCalendar.get(Calendar.WEEK_OF_MONTH) - 1 weeklyExpenses[weekOfMonth] = value } weeklyExpenses.mapIndexed { index, value -> index.toFloat() to value } } } "Monthly" -> { xValueProcessor = { expenses -> val monthlyExpenses = MutableList(12) { 0f } expenses.forEach { (value, date) -> startCalendar.time = date val month = startCalendar.get(Calendar.MONTH) monthlyExpenses[month] = value } monthlyExpenses.mapIndexed { index, value -> index.toFloat() to value } } } "Yearly" -> { xValueProcessor = { expenses -> val yearlyExpenses = MutableList(5) { 0f } val yearNow = Calendar.getInstance().get(Calendar.YEAR) expenses.forEach { (value, date) -> startCalendar.time = date val year = startCalendar.get(Calendar.YEAR) val index = year - (yearNow - 4) yearlyExpenses[index] = value } yearlyExpenses.mapIndexed { index, value -> index.toFloat() to value } } } } chartEntries.value = entriesOf(*xValueProcessor(expenses).toTypedArray()) } LaunchedEffect(Unit) { fetchExpensesData(timeFrames[selectedIndex.value]) } Column(modifier = Modifier.padding(paddingValues)) { // ... ProvideChartStyle(chartStyle = m3ChartStyle()) { Chart( chart = columnChart(), chartModelProducer = chartModelProducer, startAxis = startAxis(), bottomAxis = bottomAxis( valueFormatter = when (selectedIndex.value) { 0 -> dailyValueFormatter 1 -> weeklyValueFormatter 2 -> monthlyValueFormatter 3 -> yearlyValueFormatter else -> DecimalFormatAxisValueFormatter() } ), ) } } } val dailyValueFormatter = object : AxisValueFormatter<AxisPosition.Horizontal.Bottom> { // ... } val weeklyValueFormatter = object : AxisValueFormatter<AxisPosition.Horizontal.Bottom> { override fun format(value: Float, label: Text): CharSequence = when (value.toInt()) { 0 -> "Week 1" 1 -> "Week 2" 2 -> "Week 3" 3 -> "Week 4" else -> "" } } val monthlyValueFormatter = object : AxisValueFormatter<AxisPosition.Horizontal.Bottom> { private val months = arrayOf("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov","Dec") override fun format(value: Float, label: Text): CharSequence = months.getOrNull(value.toInt()) ?: "" } val yearlyValueFormatter = object : AxisValueFormatter<AxisPosition.Horizontal.Bottom> { override fun format(value: Float, label: Text): CharSequence { val currentYear = Calendar.getInstance().get(Calendar.YEAR) val year = currentYear - 4 + value.toInt() return year.toString() } }This complete code includes all four timeframes for the X-axis labels and handles processing of the fetched data for all timeframes. Additionally, based on the selected timeframe, it assigns the correct value formatter for the bottom axis.