Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adjust the number of grid lines in a SwiftUI Chart

I am trying to adjust (reduce) the number of gridlines in my SwiftUI Chart.

I have the following code:

Chart() {
    ForEach(self.viewModel.downloadHistory) { item in
        LineMark(x: .value(String.empty, item.timestamp), y: .value(String.empty, item.value.floatValue))
            .interpolationMethod(.stepCenter)
            .foregroundStyle(Colors.download)
    }
}
.chartXAxis(.hidden)
.frame(height: 64.0)
.gridColumnAlignment(.center)
.chartYAxis() {
    AxisMarks() { value in
        AxisGridLine(centered: true, stroke: StrokeStyle(dash: [4.0, 4.0]))
        AxisValueLabel()
        {
            if let value = value.as(UInt64.self)
            {
                Text(DiskUtilities.toSpeedNoComma(value))
            }
        }
    }
}
.padding()

This results in the following chart:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Chart with too many labels

I like the design, however, I would like to:

  • Either reduce the number of gridlines.
  • Or only show the text at the 0%, 50% and 100% line. Is this possible?

Is either of those two options possible?

>Solution :

AxisMarks has various initializers that take parameters. The parameter you’re interested in is values, which can be either AxisMarkValues or an array of some Plottable.

Try AxisMarkValues.automatic(desiredCount: 3).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading