python - 更改 Altair 折线图和面积图中的步长宽度

标签 python altair vega-lite

我尝试构建一个折线图来显示全年每个月的值。我还想填补超过阈值的月份。我对线条和填充的最后一个值的外观有疑问。

import altair as alt
from vega_datasets import data

source = data.stocks()
year_data = source[source.date.dt.year == 2007]

line = alt.Chart(year_data, width=600).mark_line(
    interpolate='step-after',
    color='red'
).encode(
    x='date',
    y='price'
).transform_filter(alt.datum.symbol == 'IBM')

fill = alt.Chart(year_data, width=600).mark_area(
    interpolate='step-after',
).encode(
    x='date',
    y='price',
).transform_filter(
    (alt.datum.symbol == 'IBM') &
    (alt.datum.price > 105)
)

fill + line

line chart for stock values

  1. 如何以与其他月份相同的宽度显示 12 月,以免在视觉上被截断?
  2. 10 月也超过了 105 的阈值,但似乎尚未填满。我该怎么做才能像其他月份一样填满它?

最佳答案

我认为您的步进插值范围问题与 Drawing line plot for a histogram 中描述的类似。我不确定是否有好的解决方案。

解决方法是执行时间分箱以将数据转换为序数并使用条形标记而不是区域:

import altair as alt
from vega_datasets import data


source = data.stocks()
year_data = source[source.date.dt.year == 2007]

line = alt.Chart(year_data, width=600).mark_line(
    interpolate='step-after',
    color='red'
).encode(
    x='month(date)',
    y='price'
).transform_filter(
    alt.datum.symbol == 'IBM'
)

line.mark_bar().transform_filter(alt.datum.price > 105) + line

enter image description here

您还可以将 x 轴设为序数,以避免 Dec 被截断。

line = alt.Chart(year_data, width=600).mark_line(
    interpolate='step',
    color='red'
).encode(
    x='month(date):O',
    y='price'
).transform_filter(
    alt.datum.symbol == 'IBM'
)

line.mark_bar().transform_filter(alt.datum.price > 105) + line

enter image description here

关于python - 更改 Altair 折线图和面积图中的步长宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73142698/

相关文章:

python - 使用字典更新 pandas DataFrame 行

python - Python 中使用 if/else 语句的 while 循环

javascript - Vega-Lite 中的平行坐标?

json - 如何为多线图数据定义json

python - 使用 nbformat 生成 Jupyter 笔记本 - Altair 图表不显示

Vega-lite 根据数据设置颜色,同时保留图例

python - 当我将 numpy 数组发送到 theano 函数中的给定参数时,为什么会收到此 Theano TypeError

python - 播放、打开和暂停从 Python 脚本执行的 VLC 命令行

python - 交互式 plotly 的 plotly 表达与Altair/Vega-Lite的 plotly 比较

python - 如何使用 Altair 按日期时间值突出显示条形