【问题标题】:Changing the width of a step in Altair line and area charts在 Altair 折线图和面积图中更改步骤的宽度
【发布时间】:2022-08-05 19:52:57
【问题描述】:

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

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

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

    标签: python altair vega-lite


    【解决方案1】:

    我认为您关于步进插值范围的问题类似于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
    

    您还可以使 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
    

    【讨论】:

    • 谢谢乔尔,这回答了问题 2)。关于 1),12 月仍然被切碎。我尝试了第二个不透明度为 0 的条形图:它延长了 12 月的宽度,但折线图仍然在 11 月结束。就我的目的而言,这已经足够了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    相关资源
    最近更新 更多