Reputation: 452
Can one make Altair plots fit the screen size, rather than have a pixel-defined width and height? I've read things about autosize
"fit"
, but I am unsure about where to specify these.
Upvotes: 8
Views: 3818
Reputation: 2837
If you are using Altair 4.0 or greater you can use properties()
and container
:
import altair as alt
from vega_datasets import data
source = data.cars()
plot = alt.Chart(source).mark_circle(size=60).encode(
x='Horsepower',
y='Miles_per_Gallon',
color='Origin',
tooltip=['Name', 'Origin', 'Horsepower', 'Miles_per_Gallon']
).properties(
width='container',
height='container'
)
This will make it responsive, note that this is the size of each plot if you have multiple it doesn't work as you would expect but instead each plot will have the size of the parent container.
Upvotes: 4
Reputation: 462
While it is true that the vega-lite determines the size of the chart itself, it is possible to treat the chart (rendered as canvas) like an image.
I used an example from w3css which applied to my vega-light charts scales the charts accordingly. Basically it is then scaled proportionally according to the surrounding container.
Example HTML generated by vega-light:
<div id="visInteractiveYear" class="vega-embed">
<canvas width="1366" height="960" class="marks" style="width: 976px; height: 686px;"></canvas>
</div>
Here the CSS snippet, that basically overwrite width/height (style) of the canvas:
canvas.marks {
max-width: 100%!important;
height: auto!important;
}
Here a test without any scaling and its original size:
Here a test with scaling to fit within the surrounding box.
If you are using interactive charts, the scaling might be a problem. I guess that the click positions are not correctly translated (since canvas is scaled, but the logic of vega does not know about it), thus strange behaviour is the result. In my case, the selection has always an offset to the mouse cursor.
Also, the user has to zoom in to be able to read the chart, since it is proportionally scaled. Probably in most cases not the ideal user-friendly way to go.
Maybe a better option is to switch to another vega-light spec, which renders the chart for the specific display size, or to switch to a different representation (e.g., a standard list), which can then easily be read on smaller displays (adaptive design).
For complex charts, opening the chart in another browser tab, might be also be a good solution. The user knows about the new tab, the mobile browser has to show only one chart/image, so there is not much clutter to worry about. Thus, it is easy to navigate/scroll in the new tab, since it only contains the chart and maybe a back/close tab button.
Upvotes: 6
Reputation: 86310
There is no way to do this. The dimensions of Altair/Vega-Lite charts are pre-determined by the chart specification and data, and cannot be made to scale with the size of the browser window.
Upvotes: 6