SwiftUI中LineChart实现多区域不同AreaMark颜色的问题
SwiftUI折线图AreaMark分区域着色问题
尝试为折线图的不同区域设置不同的AreaMark颜色,但均未成功。以下是两种尝试的实现方案及效果说明:
方案一代码
struct Value: Identifiable { var x: String var y: Int var color: String var id: UUID = UUID() } struct ContentView12: View { let data: [Value] = [ .init(x: "0", y: 3, color: "blue"), .init(x: "1", y: 4, color: "blue"), .init(x: "2", y: 5, color: "blue"), .init(x: "3", y: 8, color: "blue"), .init(x: "4", y: -6, color: "red"), .init(x: "5", y: -4, color: "red"), .init(x: "6", y: -6, color: "red"), .init(x: "7", y: -8, color: "red"), .init(x: "8", y: 10, color: "blue"), .init(x: "9", y: 8, color: "blue"), .init(x: "10", y: 5, color: "blue"), .init(x: "11", y: 7, color: "blue"), .init(x: "12", y: 10, color: "blue") ] var body: some View { VStack { Chart(data) { v in LineMark( x: .value("x", v.x), y: .value("y", v.y) ) .interpolationMethod(.linear) .foregroundStyle(Color.black) AreaMark( x: .value("x", v.x), y: .value("y", v.y) ) .interpolationMethod(.linear) .foregroundStyle(by: .value("area", v.color)) } .chartForegroundStyleScale([ "red": Color.red, "blue": Color.blue, "green": Color.green ]) } .frame(maxHeight: 300) } }
效果:AreaMark未按数据中设定的颜色分区域显示,不符合预期。
方案二代码
Chart(lineModel) { cost in LineMark( x: .value("Date", cost.date), y: .value("Price", cost.amount) ) AreaMark( x: .value("Date", cost.date), y: .value("Price", cost.amount), stacking: .unstacked ) .foregroundStyle(by: .value("Price", cost.amount >= 0 ? "blue" : "red")) } .chartForegroundStyleScale([ "red": Color.red, "blue": Color.blue ])
效果:同样未实现按数值正负分区域着色的预期,AreaMark颜色显示不符合要求。
内容的提问来源于stack exchange,提问作者Vollan
相关产品推荐
相关产品推荐

