-1

I have a simple graph (made using Swift Charts framework) where I am showing the percentage of something over time. The x-axis is the time here and y-axis is the percentage. Ergo, I think if the values in y-axis would be like 25%, 50%, etc., it would make more sense to the user.

How can I customize the y-axis values and add a symbol (in this case a %) at the end?

This is the code so far:

Chart(data, id: \.date) { datum in
    LineMark(
        x: .value("Date", datum.date, unit: .day),
        y: .value("Done", datum.doneCount * 100 / (datum.doneCount + datum.notDoneCount))
    )
    .interpolationMethod(.catmullRom)
    .foregroundStyle(Color.orange)
}
.chartXAxis {
    AxisMarks(values: .stride(by: .day))
}

enter image description here

Ram Patra
  • 16,266
  • 13
  • 66
  • 81

1 Answers1

3

Just add this code block to your Chart

.chartYAxis {
   AxisMarks() {
       let value = $0.as(Int.self)!
       AxisValueLabel {
           Text("\(value)%")
       }
   }
}

Your Chart will then show 0%, 25%, ... as labels

THUB
  • 49
  • 2
  • 1
    This works however the horizontal lines (in the background) disappear if I add this code, any ideas? – Ram Patra Jan 19 '23 at 16:35
  • You can add `AxisTick()` and `AxisGridLine()` as shown here: https://developer.apple.com/forums/thread/707868 – jtbandes Feb 08 '23 at 23:43
  • I'd not multiply the doneCount with 100. Instead you could use the original decimal number and normat the value with NumberFormatter() using numberFormatter.numberStyle = .percent. In this way the formatting would not be hardcoded and for example space between number and % would come from common formatting styles. – Pomo-J Aug 08 '23 at 17:02