英文:
Swift Charts - changing the X axis literals
问题
I am moving my charts over from Daniel Gindi to Apple's Chart and haven't worked out how to control the X axis labels.
The X axis generates a daily angle from day 1 to 365 for the year, so is an integer. I want to display the months of the year, as shown in the previous version of the chart.
Is it possible to use .chartXScale for this purpose? I am not sure how to get it to accept strings or if I need to try a different approach.
var monthValues: [String] = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"]
Chart{
ForEach(dayTilt) {item in
LineMark(
...
)
}
.frame(height: 360)
.chartXScale(domain: monthValues[0...11])
英文:
I am moving my charts over from Daniel Gindi to Apple's Chart and haven't worked out how to control the X axis labels.
The X axis generates a daily angle from day 1 to 365 for the year, so is an integer. I want to display the months of the year, as shown in the previous version of the chart.
Is it possible to use .chartXScale for this purpose? I am not sure how to get it to accept strings or if I need to try a different approach.
var monthValues: [String] = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec"]
Chart{
ForEach(dayTilt) {item in
LineMark(
...
)
}
.frame(height: 360)
.chartXScale(domain: monthValues[0...11])
答案1
得分: 1
你可能应该存储一个Date
而不是Int
来表示日期,可以像这样修改代码:
struct DayTilt: Identifiable {
internal init(day: Int, value: Float) {
date = Calendar.current.date(from: DateComponents(day: day))!
self.value = value
}
let id = UUID()
let date: Date
let value: Float
}
然后你可以使用以下的PlottableValue
函数:
value(_:date:unit:calendar:)
例如:
struct ContentView: View {
@State var dayTilts: [DayTilt] = …
var body: some View {
Chart(dayTilts) { dayTilt in
LineMark(x: .value("Date", dayTilt.date, unit: .day),
y: .value("Angle", dayTilt.value))
}
.padding()
}
}
英文:
You should probably store a Date
rather than an Int
for a day, so something like:
struct DayTilt: Identifiable {
internal init(day: Int, value: Float) {
date = Calendar.current.date(from: DateComponents(day: day))!
self.value = value
}
let id = UUID()
let date: Date
let value: Float
}
then you can use the following PlottableValue
value(_:date:unit:calendar:)
e.g.
struct ContentView: View {
@State var dayTilts: [DayTilt] = …
var body: some View {
Chart(dayTilts) { dayTilt in
LineMark(x: .value("Date", dayTilt.date, unit: .day),
y: .value("Angle", dayTilt.value))
}
.padding()
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论