问题
Apologies for not being able to provide a lot of code, everything is interconnected and it's not possible right now.
My issue is I created a point chart that serves as an "interactive legend".
legend = alt.Chart(source).mark_point().encode(
y=alt.Y('STATE', axis=alt.Axis(orient='right')),
).add_selection(
select_state
)
The problem is that 50 states are listed. As a result the chart becomes very long and prevents everything from fitting on a single screen.
Is there any way to somehow wrap this chart so that it is shown in multiple columns? I don't think this would be possible given that the legend is a single column point chart.
Is there any way to convert this into some sort of structure in Altair that makes it possible to wrap into multiple columns that is not a chart?
Alternatively, is there a way to reposition my slider? It appears way at the bottom :( If it appeared on the top, I think it would be able to appear on the same screen as everything else and so the legend chart wouldn't be so much of an issue.
slider = alt.binding_range(min=1992, max=2016, step=1)
# 1st selection filter
select_year = alt.selection_single(name="YEAR", fields=['YEAR'],
bind=slider, init={'YEAR': 1992})
回答1:
You can specify the encoding's legend.columns
property to control the number of columns in the legend. For example, using the cars dataset:
import altair as alt
from vega_datasets import data
alt.Chart(data.cars.url).mark_point().encode(
x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color=alt.Color('Name:N', legend=alt.Legend(columns=8))
).properties(
# Adjust chart width and height to match size of legend
width=600,
height=600
)
With this many attribues, though, legends become not very useful in practice. You might consider a tooltip
encoding instead to surface detailed information like this.
回答2:
Check out this example:
import altair as alt
from vega_datasets import data
source = data.unemployment_across_industries.url
selection = alt.selection_multi(fields=['series'], bind='legend')
alt.Chart(source).mark_area().encode(
alt.X('yearmonth(date):T', axis=alt.Axis(domain=False, format='%Y', tickSize=0)),
alt.Y('sum(count):Q', stack='center', axis=None),
alt.Color('series:N', scale=alt.Scale(scheme='category20b')),
opacity=alt.condition(selection, alt.value(1), alt.value(0.2))
).add_selection(
selection
)
Reference: https://altair-viz.github.io/gallery/interactive_legend.html
来源:https://stackoverflow.com/questions/56758828/making-a-legend-into-multiple-columns-in-altair