vojtamolda / Plotly.swift

Interactive data visualization library for Swift
https://vojtamolda.github.io/Plotly.swift/
MIT License
82 stars 8 forks source link

Layout axis system layout.xAxis/yAxis properties are missing from JSON if figure contains more than one trace #18

Closed vojtamolda closed 3 years ago

vojtamolda commented 3 years ago

The following code snippet:

Figure(
    data: [
        Scatter(x: [1, 2], y: [3, 4]),
        Scatter(x: [1, 2], y: [4, 5])
    ],
    layout: Layout(
        xAxis: [ Layout.XAxis(title: "X Label") ],
        yAxis: [ Layout.YAxis(title: "Y Label") ]
   )
)

Produces incorrect JSON representation. The xaxis1 and yaxis1 attributes of the layout are empty. The titles on the axes therefore don't show up when the figure is rendered.

Here's the invalid JSON that gets produced in v0.4.0:

{
    "data": [
        {"trace": "scatter", "x": [1, 2], "y": [3, 4] },
        {"trace": "scatter", "x": [1, 2], "y": [4, 5] }
    ],
    "layout": {
        "xaxis1": { },
        "yaxis1": { }
    }
}

The reason why it happens is that each trace gets its own instance of the Layout.XAxis(uid: 1) assigned to the xAxis property. The Figure constructors does a little "dance" and collects these properties from all traces and adds them to the layout.

This way the layout ends up with multiple XAxis objects that don't have unique uid. When the entire figure gets encoded to JSON, the encoder keeps overwriting the value for the xaxis1 key over and over the value that is acually visible is the one that happens to be stored the last.

vojtamolda commented 3 years ago

Fixed in release 0.5.0.