You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Swift Charts库调整坐标轴位置与样式?

SwiftUI Charts 柱状图坐标轴修改方案

需求说明

  • 将Y轴(含刻度)移至左侧
  • 将坐标轴设置为白色粗线

修改后的完整代码

import SwiftUI
import Charts
import PlaygroundSupport

struct BarChartExample: View {
    let data = [
        ("A", "Z", 5),
        ("A", "Z", 5),
        ("B", "Z", 10),
        ("C", "Y", 7),
        ("D", "Y", 3),
        ("E", "Y", 12),
        ("B", "Y", 10),
        ("C", "X", 7),
        ("D", "X", 3),
        ("E", "X", 12)
    ]

    var body: some View {
        Chart {
            ForEach(data, id: \.0) { item in
                BarMark(
                    x: .value("Category", item.0),
                    y: .value("Value", item.2),
                    stacking: .standard
                )
                .foregroundStyle(by: .value("Category", item.1))
            }
        }
        // 修改X轴样式:白色粗线刻度和轴线
        .chartXAxis {
            AxisMarks(position: .bottom) {
                AxisTick(centered: true, length: 10, stroke: StrokeStyle(lineWidth: 2, color: .white))
                AxisGridLine(stroke: StrokeStyle(lineWidth: 2, color: .white))
                AxisValueLabel(textColor: .white)
            }
        }
        // 修改Y轴位置到左侧,并设置白色粗线
        .chartYAxis {
            AxisMarks(position: .leading) { value in
                AxisTick(length: 10, stroke: StrokeStyle(lineWidth: 2, color: .white))
                AxisGridLine(stroke: StrokeStyle(lineWidth: 2, color: .white))
                AxisValueLabel(textColor: .white)
            }
        }
        .frame(width: 300, height: 200)
        .padding()
        .background(Color.black) // 添加深色背景,匹配预期图的视觉效果
    }
}

PlaygroundPage.current.setLiveView(BarChartExample())

关键修改点解析

  1. Y轴移至左侧:在.chartYAxis的AxisMarks初始化时指定position: .leading,直接将Y轴及刻度移到图表左侧。
  2. 白色粗线坐标轴:
    • 对X、Y轴的AxisTick(刻度线)和AxisGridLine(轴线)设置stroke参数,指定线宽为2、颜色为白色。
    • 同时将轴标签文字颜色设为白色,配合深色背景更清晰。
  3. 深色背景:添加.background(Color.black)匹配预期效果图的深色底色,让白色坐标轴更突出。

内容的提问来源于stack exchange,提问作者Konrad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 10:17:16