Merge two legends in altair

Viewed 539

I have a scatter plot in altair where I am representing a column using both shape and color. I would like to have a single legend with both pieces of information, but instead I am getting two legends, one for shape and another for color.

enter image description here

The code is as follows. See this notebook for a reproducible example (you will need to enter your google credentials to load the data).

import altair as alt
alt.themes.enable('fivethirtyeight')
selection = alt.selection_multi(fields=['Domain'], bind='legend')

chart = alt.Chart(df, width=1100, height=600, 
          title="Parameter count of ML systems through time")\
.mark_point(size=120, filled=False).encode(
  x=alt.X('Publication date:T'),
  y=alt.Y('Parameters:Q',
          scale=alt.Scale(type='log', domain=(1, 3e13)), 
          axis=alt.Axis(format=".1e")),
  color=alt.Color('Domain',  
                  sort=['Vision', 'Language', 'Games', 'Other'],
                  legend=alt.Legend(
                      values = ['Vision', 'Language', 'Games', 'Other'],),),
  shape = alt.Shape('Domain'),#, legend=None),
  tooltip=['System', 
           'Reference', 
           'Publication date', 
           alt.Tooltip('Parameters', format=".1e"), 
           'Domain'],
  opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
)

regression = chart.transform_regression(
    on="Publication date", 
    regression="Parameters",  
    method = 'exp',
    groupby=["Domain"],
).mark_line(point=False, strokeDash=[10,5], clip=True)

alt.layer(chart.add_selection(selection), regression).configure_axis(
    labelFontSize=20,titleFontSize=30).configure_legend(
    titleFontSize=20,
    labelFontSize =18,
    gradientLength=400,
    gradientThickness=30,
    symbolSize = 130,
)

How can I merge both legends into a single one?

1 Answers

You can set the legend to None in the line chart for shape and color and then use resolve_scale as per the comments on the question:

import altair as alt
from vega_datasets import data


df = data.cars()
selection = alt.selection_multi(fields=['Origin'], bind='legend')

chart = alt.Chart(df).mark_point(filled=False).encode(
  x=alt.X('Acceleration'),
  y=alt.Y('Horsepower',scale=alt.Scale(type='log'), axis=alt.Axis(format=".1e")),
  color='Origin',
  shape='Origin',
  opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
)

regression = chart.transform_regression(
    on="Acceleration", regression="Horsepower", groupby=["Origin"]
).mark_line(
).encode(color=alt.Color('Origin', legend=None), shape=alt.Shape('Origin', legend=None))

(alt.layer(chart, regression)
 .resolve_scale(shape='independent', color='independent')
 .add_selection(selection))

enter image description here

Related