简体   繁体   中英

How to add a legend in altair layered plots

So I have the following code:

workload_df = pd.DataFrame({
'index': pd.to_datetime(['01.02.2010', '01.03.2010', '01.04.2010']),
'measure': [100, 90, 120],
'measure_max': [80, 100, 150],
})

measure_max_plot = alt.Chart(workload_df).mark_bar(color = 'lightgreen', text = 'measure_max').encode(
    alt.X('index', title = '', axis = alt.Axis(labelAngle = -45, labelOverlap = False)),
    alt.Y('measure_max', title = '')
)

measure_plot = alt.Chart(workload_df).mark_bar(text = 'measure').encode(
  x = alt.X('index', title = 'X', axis = alt.Axis(labelAngle = -45, labelOverlap = False)), 
  y = alt.Y('measure', title = 'Y'),

  color=alt.condition(
    alt.datum.measure > alt.datum.measure_max,  
    alt.value('red'),     
    alt.value('steelblue')   
  )
)
altair_plot = alt.layer(measure_max_plot, measure_plot)
st.altair_chart(altair_plot, use_container_width=True)

I already tried adding a legend, by using this solution: Add legend to line & bars to Altair chart without using size/color

But got a weird error all the time or got a legend without any plotted data.

Can anyone help me with that?

In order to add a legend to your chart, you will need an encoding that the legend will represent. For example, here's how you might add a color encoding that will generate a color legend:

measure_max_plot = alt.Chart(workload_df).transform_calculate(
    color='"measure_max"'
).mark_bar(text = 'measure_max').encode(
    alt.X('index', title = '', axis = alt.Axis(labelAngle = -45, labelOverlap = False)),
    alt.Y('measure_max', title = ''),
    alt.Color('color:N')
)

measure_plot = alt.Chart(workload_df).transform_calculate(
  color="datum.measure > datum.measure_max ? 'bigger' : 'smaller'"
).mark_bar(text = 'measure').encode(
  x = alt.X('index', title = 'X', axis = alt.Axis(labelAngle = -45, labelOverlap = False)), 
  y = alt.Y('measure', title = 'Y'),
  color = alt.Color('color:N', scale=alt.Scale(range=['red', 'lightgreen', 'steelblue']))
)
altair_plot = alt.layer(measure_max_plot, measure_plot)

在此处输入图像描述

Notice that by default, the color scale is shared between the two layered charts. This behavior can be fine-tuned using the Scale & guide resolution API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM