简体   繁体   English

如何使用 mark_rule() 在 Altair 图表中显示一条垂直线

[英]How to show a vertical line in an Altair chart using mark_rule()

I am creating an histogram using Python & Altair.我正在使用 Python 和 Altair 创建直方图。 I am able to include a vertical line as the mean, which works, but the code for the first Quartile (25th quantile) does not produce a vertical line.我可以包含一条垂直线作为平均值,这是可行的,但第一个四分位数(第 25 个分位数)的代码不会产生一条垂直线。

I assume it is based that I use a numpy function to calculate the first quartile.我认为这是基于我使用 numpy 函数来计算第一个四分位数。 But I am unsure how to do it differently.但我不确定如何以不同的方式做到这一点。

What am I missing?我错过了什么? Thank you!谢谢!

import pandas as pd
import numpy as np
import altair as alt

df = pd.util.testing.makeDataFrame()

chart = (
    alt.Chart(df)
    .mark_bar()
    .encode(alt.X("A:Q", bin = True), y = "count()")
    .properties(width = 800, height = 300)
) 

# create mean rule ***WORKS***
mean = (
    alt.Chart(df)
    .mark_rule()
    .encode(
        x = "mean(A):Q"
    )
)

chart + mean

在此处输入图片说明

# create Q1 rule *** vertical line is NOT showing***
Q1 = (
    alt.Chart(df)
    .mark_rule()
    .encode(
        x = "np.quantile(A, 0.25):Q"
    )
)

chart + Q1

在此处输入图片说明

Any suggestions?有什么建议么? Thank you!谢谢!

Altair encoding strings do not parse arbitrary python code, so calling numpy functions will not work. Altair 编码字符串不会解析任意的 Python 代码,因此调用 numpy 函数将不起作用。

For quantiles in Altair, you can use thequantile transform .对于 Altair 中的分位数,您可以使用quantile transform Here is an example with your data:以下是您的数据示例:

Q1 = (
    alt.Chart(df)
    .transform_quantile('A', probs=[0.25], as_=['prob', 'value'])
    .mark_rule()
    .encode(
        x = "value:Q"
    )
)

chart + Q1

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM