swiftuichartslinemark

In SwiftUI Charts, is it possible to change the color of linemarks and areamarks points based on custom criteria (not y)?


I want to draw an AreaMark chart with SwiftUI, with different colors based on some properties of my points that are not y, like this: Chart with different colors

Setting a foregroundStyle for each point will set the color of the last point. It looks pretty easy to set the color of linemarks and areamarks based on the y value, but I can't find how to base it on custom criteria. Is it possible to do it with Charts?


Solution

  • Ok, in the end I managed to do it. For those who would like to do the same thing, the idea is to create an image of height 1 and of width of the data array count.

    Then, use the image shape style:

    .foregroundStyle(.image(chartColors, scale: <Data length>))
    

    Depending on the data size, you may want to duplicate the pixels to reduce the blur. The scale needs to be adapted then (divide by the number of duplications. Result