如何使用mark_rule()在牛郎星图表中显示垂直线

2024-03-29 00:27:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python&;牵牛星。我可以包括一条垂直线作为平均值,这是可行的,但是第一个四分位数(25分位数)的代码不会产生垂直线

我假设我使用numpy函数来计算第一个四分位数。但我不知道如何做不同的

我错过了什么?谢谢大家!

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

enter image description here

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

chart + Q1

enter image description here

有什么建议吗?谢谢大家!


Tags: importnumpydfaschartmeanaltrule
1条回答
网友
1楼 · 发布于 2024-03-29 00:27:27

Altair编码字符串不会解析任意python代码,因此调用numpy函数将不起作用

对于Altair中的分位数,可以使用quantile transform。以下是您的数据示例:

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

chart + Q1

enter image description here

相关问题 更多 >