Aleksandr Shepelev
Aleksandr Shepelev

Reputation: 11

cannot translate vega-light color condition to altair

I have this vlspec (it is working) I need to translate it to altair

vlspec.encoding.color = 
{
   "scale": {
       "type": "threshold",
       "domain": [
           "< 10",
           "10 - 70",
           "≥ 70"
       ],
       "range": [
           "#cb5047",
           "#f1ad4b",
           "#486d49"
       ]
    },

    "condition": [
        {
            "test": {
                "field": "rate",
                "lt": 10
            },
            "value": "#cb5047"
        },
        {
            "test": {
                "field": "rate",
                "lt": 70
            },
            "value": "#f1ad4b"
        },
        {
            "test": {
                "field": "rate",
                "gte": 70
            },
            "value": "#486d49"
        }
    ]
}

I trying a lot of options for alt.Condition, but failed to translate this to altair. Can somebody help please?

Upvotes: 0

Views: 68

Answers (1)

jakevdp
jakevdp

Reputation: 86463

Altair uses Vega-Lite 4.8, in which it is not permitted to include a "scale" specification in a "value" encoding (it has no effect anyway). Once you take that out, you can use your Vega-Lite specification directly in your Altair chart. For example:

import altair as alt
import pandas as pd

df = pd.DataFrame({
    'x': [1, 2, 3, 4],
    'rate': [5, 20, 40, 80]
})

color = {
    "condition": [
        {
            "test": {
                "field": "rate",
                "lt": 10
            },
            "value": "#cb5047"
        },
        {
            "test": {
                "field": "rate",
                "lt": 70
            },
            "value": "#f1ad4b"
        },
        {
            "test": {
                "field": "rate",
                "gte": 70
            },
            "value": "#486d49"
        }
    ]
}

alt.Chart(df).mark_point().encode(
    x='x',
    y='rate',
    color=color
)

enter image description here

Upvotes: 1

Related Questions