UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Different color bars in the same barmark chart

Forums > SwiftUI

Hi experts :)

I have a barmark chart with 6 bars. It works fine but I want the first 3 bars to be red and the second 3 bars to be green.

Any idea how I do this?

    struct Item: Identifiable {
        let id = UUID()
        let month: String
        let visitValue: Int
    }

    var myItems = [Item]()
    let items:  [Item] = [

                // Highest perfoming Months
                Item(month: highestLowestMonths.mthHighestName[0],
                visitValue: Int(highestLowestMonths.mthHighestRevenue[0])),

                Item(month: highestLowestMonths.mthHighestName[1],
                visitValue: Int(highestLowestMonths.mthHighestRevenue[1])),

                Item(month: highestLowestMonths.mthHighestName[2],
                visitValue: Int(highestLowestMonths.mthHighestRevenue[2])),

                // Lowest perfoming Months
                Item(month: highestLowestMonths.mthLowestName[0],
                visitValue: Int(highestLowestMonths.mthLowestRevenue[0])),

                Item(month: highestLowestMonths.mthLowestName[1],
                visitValue: Int(highestLowestMonths.mthLowestRevenue[1])),

                Item(month: highestLowestMonths.mthLowestName[2],
                visitValue: Int(highestLowestMonths.mthLowestRevenue[2])),
    ]

    var body: some View {

                Chart {
                    // High and low monthly performers chart
                    ForEach(items) { items in
                        BarMark(
                            x: .value("Month", items.month),
                            y: .value("sales Revenue", items.visitValue)
                        )
                        .foregroundStyle(.green.opacity(0.8))

                        RuleMark(
                            y: .value("xxx", contactAnalyticsDataMonthlyAverages.eaAverageVisitValue)
                            )
                            .foregroundStyle(.gray)
                            .lineStyle(StrokeStyle(lineWidth: 2))
                            .annotation(position: .top, alignment: .leading)
                        {
                                Text("FIXTHIS \(contactAnalyticsDataMonthlyAverages.eaAverageVisitValue, format: .number)")
                                    .font(.system(size: 12, weight: .semibold, design: .rounded))
                                    .foregroundStyle(.blue)
                            }
                    }
                }

                .chartForegroundStyleScale([
                    "zzz": Color(.green)
                     ])
                .chartLegend(position: .top, alignment: .bottomTrailing)
                .chartYAxis(.hidden)

                // Chart has been tapped. display large version.
                .onTapGesture {
                    print("mob: High and low monthly performers chart tapped")
                    showLargeChart = true
                    }
                    .sheet(isPresented: $showLargeChart) {
                    summaryChartLarge()
                    }
            }
        }

1      

You need a variable in your Item for the color. F.e. var color: String

There is a modifier you can use on your BarMark

.foregroundStyle(by: .value("Result Color", item.color))

Then there is another modifier for the chart itself.

.chartForegroundStyleScale([
            "Red": .red,
            "Green": .green
        ])

1      

Hi Hatsushira, thank you . I did that and now I have a very strange runtime error. I will start a new question for that issue.

1      

@flaneur:

Please remember to mark his answer as "Solved". Only you can do this.

1      

SOLVED. Thank you!

1      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.