You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Altair库:如何保存高分辨率图表

Adjusting Chart Resolution in Altair for PNG/SVG Exports

Great question! When working with Altair, tweaking resolution for PNG or SVG exports relies on understanding how it interacts with Vega-Lite's rendering under the hood. Let's break this down by file format:

For PNG (Raster Images)

PNG is a raster format, so resolution depends on how many pixels are rendered for your chart. The default output can feel low-res, but you can easily scale up the rendering using the scale parameter in the save() method. This works with both Altair's built-in saver backends (altair_saver or Selenium).

Here's a concrete example:

import altair as alt
from vega_datasets import data

# Create a sample scatter plot
cars = data.cars.url
chart = alt.Chart(cars).mark_point(size=60).encode(
    x='Horsepower:Q',
    y='Miles_per_Gallon:Q',
    color='Origin:N'
)

# Save with 3x the default resolution (scale=3)
chart.save('high_res_cars.png', scale=3)
  • The scale value multiplies the base pixel dimensions of your chart. A scale of 3 means every pixel in the default chart becomes 3x3 pixels in the output PNG, tripling the effective resolution. Adjust this number (2, 3, 4, etc.) based on how crisp you need the image to be.

Note on Dependencies

Make sure you have the necessary saver tools installed:

  • For the simplest setup, install altair_saver:
    pip install altair_saver
    
  • If you run into compatibility issues, use Selenium (requires a browser driver like ChromeDriver):
    pip install selenium
    

For SVG (Vector Graphics)

SVG is a vector format, which means it doesn't have a fixed resolution—it will stay perfectly sharp no matter how much you zoom in or scale it. That said, you can control the base dimensions of the SVG to ensure it renders well at specific sizes (e.g., for print or large displays):

# Set explicit width and height for the SVG
chart = chart.properties(
    width=1000,
    height=700
)

# Save the scalable SVG
chart.save('scalable_cars.svg')

If you later need a high-res PNG from this SVG, you can use tools like Inkscape or ImageMagick to render it at your desired DPI, but using Altair's save() with scale directly is usually faster for Python workflows.

内容的提问来源于stack exchange,提问作者Steven Kaye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 11:04:08