vega / altair

Declarative statistical visualization library for Python
https://altair-viz.github.io/
BSD 3-Clause "New" or "Revised" License
9.21k stars 783 forks source link

specifying domain/range for color scale puts everything from domain/range in legend even if it's not used #2075

Closed jowens closed 11 months ago

jowens commented 4 years ago
import altair as alt
import pandas as pd

domain = [
    "A",
    "B",
    "C",
]
range = [
    "#4daf4a",
    "#984ea3",
    "#ff7f00",
]

df = pd.DataFrame({"x": [1, 2, 3], "y": [3, 2, 1], "label": ["A", "B", "A"]})

alt.Chart(df).mark_point().encode(
    x="x",
    y="y",
    color=alt.Color("label", scale=alt.Scale(domain=domain, range=range)),
    shape="label",
)

visualization

If every label is represented:

df = pd.DataFrame({"x": [1, 2, 3], "y": [3, 2, 1], "label": ["A", "B", "C"]})

alt.Chart(df).mark_point().encode(
    x="x",
    y="y",
    color=alt.Color("label", scale=alt.Scale(domain=domain, range=range)),
    shape="label",
)

visualization (1)

I would prefer that

Thanks for lookin'!

jakevdp commented 4 years ago

The first point is by design: specifying a domain and range is how you make the legend represent points that are not in the data (for example, when dynamically filtering).

The second point is a known issue; see #1785

jowens commented 4 years ago

OK. Other than filtering the domain and range Scale arrays once I see the data, any other way to make it reflect the actual contents of the data? (Might be potentially interesting to make this an option to Scale, legendOnlyReflectsDataBool, that sort of thing.)

(The reason I'm using a domain/range is to get the colors consistent between different plots for the same labels. If there's another way to do this, I'm all ears.)

Thanks.

jakevdp commented 4 years ago

I don't know of any way to make an explicit domain/range respond to the contents of the data. You might ask on the vega-lite lists.

jowens commented 4 years ago

@jakevdp, @kanitw has a vega-lite hack (using "signal") that you might want to peek at, https://github.com/vega/vega-lite/issues/6310#issuecomment-612121376

joelostblom commented 11 months ago

Since this is tracked in https://github.com/vega/vega/issues/2535 and https://github.com/altair-viz/altair/issues/1785, and it needs to be implemented in VL for it to become available in altair I'm closing this issue.