我正在使用新的swift图表框架来显示一些数据。在寻求手动控制x轴AxisValueLabels的频率以及调整颜色时,我实现了以下内容:
AxisMarks(values: .automatic(desiredCount: 11, roundLowerBound: true, roundUpperBound: true)) { _ in
AxisGridLine(stroke: .init(lineWidth: 1)).foregroundStyle(Color.orange)
AxisValueLabel().foregroundStyle(Color.orange).font(.subheadline).offset(x: -10) } }
我想显示每个x轴值的值(有11个点,它只显示10个(。我已经尝试了无数种方法,但无法通过调整desiredCount参数使其显示出应有的效果。希望在这件事上能得到任何帮助。。
import SwiftUI
import Foundation
import Charts
struct FakeData: Codable {
var questionAndAnswers: [Int: Int]
var timePerQuestion: [Double]
var date: Date = .now
}
extension FakeData {
static let oneFakeInstance = FakeData(questionAndAnswers: [1875: 1875,
1890: 1890,
1980: 1980,
2112: 2112,
2726: 2726,
4088: 4088,
4284: 4284,
4784: 4784,
4800: 4800,
663: 663,
1098:1098], timePerQuestion: [
28.700000000000138,
11.600000000000165,
12.00000000000017,
25.599999999999376,
11.999999999999318,
19.19999999999891,
12.799999999999272,
7.199999999999605,
11.699999999999335,
39.299999999997766,19.299999999997766
])
}
struct CH1: View {
func convertToShowable(_ QuizquestionAnswers: [Int: Int] = FakeData.oneFakeInstance.questionAndAnswers, _ quizTimes: [Double] = FakeData.oneFakeInstance.timePerQuestion) -> [Int: Double] {
var time_per_question: [Int: Double] = [:]
for (index, key_value) in QuizquestionAnswers.enumerated() {
if key_value.value == key_value.key {
time_per_question[index] = quizTimes[index]
}
}
return time_per_question
}
var body: some View {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
VStack {
Chart {
ForEach(convertToShowable().sorted(by: {$0.key < $1.key}), id: .key) { key, value in
BarMark(x: .value("Question", key),
y: .value("Time", value))
.foregroundStyle(Color.white)
}
}
.chartYAxis {
AxisMarks(values: .automatic) { _ in
AxisValueLabel().foregroundStyle(Color.orange).offset(x: 10).font(.subheadline)
}
}
.chartXAxis {
AxisMarks(values: .automatic(desiredCount: 11, roundLowerBound: true, roundUpperBound: true)) { _ in
AxisGridLine(stroke: .init(lineWidth: 1)).foregroundStyle(Color.orange)
AxisValueLabel().foregroundStyle(Color.orange).font(.subheadline).offset(x: -10)
}
}
.frame(width: 350, height: 250)}}}}
```[![You can see there should be a 10 here, but there is nothing][1]][1]
[1]: https://i.stack.imgur.com/sYfXa.png
尝试显示您的11点:
.chartXScale(domain: 0...11)
您正在寻找使用AxisMarks(preset: .aligned, values: ..
。然后您也可以删除偏移。