SwiftCharts: how to manage colors and groupings

I want to draw a chart where I have two line marks (one for each child each) and behind it area marks for percentiles. If I don't add any foregroundStyle then the line marks get connected.

struct GrowthChart: View
{

	@ChartContentBuilder
	func oneSlice(row: PercentileRow, slice: Slice) -> some ChartContent
	{
		AreaMark(
			x: .value("Day", row.month),
			yStart: .value("Max", row.dictionary[slice.startKey]!),
			yEnd: .value("Min", row.dictionary[slice.endKey]!)
		)
		.foregroundStyle(by: .value("Percentile", slice.number))
	}

	let percentileColors: [Color] = [
							.blue.opacity(0.1),
						  .blue.opacity(0.2),
						  .blue.opacity(0.3),
						  .blue.opacity(0.4),
						  .blue.opacity(0.5),
						  .blue.opacity(0.4),
						  .blue.opacity(0.3),
						  .blue.opacity(0.2),
						  .blue.opacity(0.1)
					  ]

	
	var body: some View
	{
		VStack {
			Chart {
				ForEach(percentiles.rows) { row in
					ForEach(slices) { slice in
						oneSlice(row: row, slice: slice)
					}
				}

				ForEach(children) { child in
					ForEach(child.data) { dataPoint in
						LineMark(
							x: .value("Month", dataPoint.month),
							y: .value("Height", dataPoint.height)
						)
						.foregroundStyle(by: .value("Name", child.name))
					}
				}
			}
			.chartForegroundStyleScale(
						range: Gradient (colors: percentileColors)
					)
			.aspectRatio(contentMode: .fit)
				.padding()
			Spacer()
		}.padding()
	}
}

I don't understand how to group the individual marks. Apparently you have to add a foregroundStyle to each with a .by specifying a category. I found this chartForegroundStyleScale in an example on the internet, but I can only get it to show this gradient. But how do I specify different colors for the LineMarks?

Answered by Oliver Drobnik in 718272022

I found that LineMark and AreaMark have a series parameter by which a series can be grouped. By doing that I can set a static foregroundStyle for my percentile area marks while using the data-based foreground styles for the actual data line marks.

Accepted Answer

I found that LineMark and AreaMark have a series parameter by which a series can be grouped. By doing that I can set a static foregroundStyle for my percentile area marks while using the data-based foreground styles for the actual data line marks.

SwiftCharts: how to manage colors and groupings
 
 
Q