SectorMark foreground style colors

Dear all, I am using SwiftUI 15.2 and I have created a donut chart using SectorMark. Now, I have three values to show in the chart. When I set up the foregroundstyle, it returns orange, blu and green colors, whereas I'd like to have different colors (e.g. red, yellow and green).

Chart(data, id: \.risultato) { dataItem in
                                            SectorMark(angle: .value("Type", dataItem.partite),
                                                       innerRadius: .ratio(0.7),
                                                       angularInset: 1.5)
                                            .foregroundStyle(by: .value("Type", dataItem.risultato))
                                            .annotation(position: .overlay){
                                                Text("\(dataItem.partite)")
                                                    .font(.caption)
                                            }
                                        }
                                .frame(height: 150)

I'm reporting the final result here below.

Do you know how I can customize them?

Thanks in advance for your support, Andrea

Answered by mhafizras in 782452022

I assume your model is something similar to this. Then add the new color property as below.

struct Data {
    let risultato: String
    let partite: Int
    // add this new property
    let color: Color
}

So in your Chart block you will need to set the color to foregroundStyle. Make sure you already set the colors in your array of data.

Chart(data, id: \.risultato) { dataItem in
    SectorMark(angle: .value("Type", dataItem.partite),
               innerRadius: .ratio(0.7),
               angularInset: 1.5)
    .foregroundStyle(dataItem.color)) // update this line
    .annotation(position: .overlay){
        Text("\(dataItem.partite)")
            .font(.caption)
    }
}
.frame(height: 150)

Hi, I'm writing here as I found a solution for the problem and hope this will be useful for anybody else.

Here below the code I've added to the chart:

This way the chart is behaving as expected.

A.

Accepted Answer

I assume your model is something similar to this. Then add the new color property as below.

struct Data {
    let risultato: String
    let partite: Int
    // add this new property
    let color: Color
}

So in your Chart block you will need to set the color to foregroundStyle. Make sure you already set the colors in your array of data.

Chart(data, id: \.risultato) { dataItem in
    SectorMark(angle: .value("Type", dataItem.partite),
               innerRadius: .ratio(0.7),
               angularInset: 1.5)
    .foregroundStyle(dataItem.color)) // update this line
    .annotation(position: .overlay){
        Text("\(dataItem.partite)")
            .font(.caption)
    }
}
.frame(height: 150)
SectorMark foreground style colors
 
 
Q