Is there a way to specify what the legend shows in Altair?

Viewed 506

I have the following graph in Altair: enter image description here

The code used to generate it is as follows:

data = pd.read_csv(data_csv)
display(data)
display(set(data['algo_score_raw']))
# First generate base graph
base = alt.Chart(data).mark_circle(opacity=1, stroke='#4c78a8').encode(
    x=alt.X('Paragraph:N', axis=None),
    y=alt.Y('Section:N', sort=list(OrderedDict.fromkeys(data['Section']))),
    size=alt.Size('algo_score_raw:Q', title="Number of Matches"),
).properties(
    width=900,
    height=500
)

# Next generate the overlying graph with the lines

lines = alt.Chart(data).mark_rule(stroke='#4c78a8').encode(
    x=alt.X('Paragraph:N', axis=alt.Axis(labelAngle=0)),
    y=alt.Y('Section:N', sort=list(OrderedDict.fromkeys(data['Section'])))
).properties(
    width=900,
    height=500
)
if max(data['algo_score_raw']) == 0:
    return lines # no circles if no matches
else:
    return base + lines

However, I don't want the decimal values in my legend; I only want 1.0, 2.0, and 3.0, because those are the only values that are actually present in my data. However, Altair seems to default to what you see above.

2 Answers

The legend is generated based on how you specify your encoding. It sounds like your data are better represented as ordered categories than as a continuous quantitative scale. You can specify this by changing the encoding type to ordinal:

    size=alt.Size('algo_score_raw:O')

You can read more about encoding types at https://altair-viz.github.io/user_guide/encoding.html

You can use alt.Legend(tickCount=2)) (labelExpr could also be helpful, see the docs for more):

import altair as alt
from vega_datasets import data


source = data.cars()
source['Acceleration'] = source['Acceleration'] / 10

chart = alt.Chart(source).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    size='Acceleration',
)
chart

enter image description here

chart.encode(size=alt.Size('Acceleration', legend=alt.Legend(tickCount=2)))

enter image description here

Related