willdale / SwiftUICharts

A charts / plotting library for SwiftUI. Works on macOS, iOS, watchOS, and tvOS and has accessibility features built in.
MIT License
837 stars 103 forks source link

Center label on xAxis #207

Open gregorpichler opened 2 years ago

gregorpichler commented 2 years ago

Hi,

how can I center the labels on the xAxis? Ideally they are centered to the according the bar.

Screenshot 2022-06-12 at 11 05 23

Sample code:

struct BarChartView: View {    
    let yAxisLabels = [...]

    let style: BarChartStyle
    var data: BarChartData

    init() {
        let set = BarDataSet(dataPoints: [
            BarChartDataPoint(value: Double.random(in: 1.0...5.0), xAxisLabel: "Mo"),
            BarChartDataPoint(value: Double.random(in: 1.0...5.0), xAxisLabel: "Tu"),
            BarChartDataPoint(value: Double.random(in: 1.0...5.0), xAxisLabel: "We"),
            BarChartDataPoint(value: Double.random(in: 1.0...5.0), xAxisLabel: "Th"),
            BarChartDataPoint(value: Double.random(in: 1.0...5.0), xAxisLabel: "Fr"),
            BarChartDataPoint(value: Double.random(in: 1.0...5.0), xAxisLabel: "Sa"),
            BarChartDataPoint(value: Double.random(in: 1.0...5.0), xAxisLabel: "Su")])
        style = BarChartStyle(yAxisNumberOfLabels: 5, yAxisLabelType: .custom)
        let barStyle = BarStyle(barWidth: 0.5, cornerRadius: .init(left: 6, right: 6), colourFrom: .barStyle, colour: .init(colour: .yellow))
        data = BarChartData(dataSets: set, yAxisLabels: yAxisLabels, barStyle: barStyle, chartStyle: style)
    }

    var body: some View {
        GeometryReader { geometry in
            BarChart(chartData: data)
                .yAxisLabels(chartData: data)
                .xAxisLabels(chartData: data)
                .frame(width: geometry.size.width, height: 200)
        }
    }
nikolafamit commented 2 years ago

Use xAxisLabel from BarChartDataPoint by adding .dataPoint(rotation: Angle()) to BarChartStyle

style = BarChartStyle(xAxisLabelsFrom: .dataPoint(rotation: Angle()), 
                                       yAxisNumberOfLabels: 5, 
                                       yAxisLabelType: .custom)
mlawlerau commented 1 year ago

Nikola, I dont think this answers the question. Gregor is asking about alignment, not where/how to supply the label values.