【问题标题】:Merge two legends in altair在 altair 中合并两个图例
【发布时间】:2021-06-21 14:52:02
【问题描述】:

我在 altair 中有一个散点图,我用形状和颜色来表示一列。我想要一个包含两条信息的图例,但我得到了两个图例,一个用于形状,另一个用于颜色。

代码如下。请参阅this notebook 以获取可重现的示例(您需要输入您的谷歌凭据才能加载数据)。

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,
)

如何将两个图例合并为一个?

【问题讨论】:

  • 也许可以将.resove_scale( color='independent', shape='independent') 添加到alt.layer()
  • @dubbbdan 谢谢你的建议。可悲的是我收到AttributeError: 'LayerChart' object has no attribute 'resove_scale'
  • 哎呀错字。应该是resolve_scale 而不是resove

标签: python data-visualization legend altair


【解决方案1】:

您可以在折线图中将图例设置为 None 以获取形状和颜色,然后根据问题上的 cmets 使用 resolve_scale

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多