如何使用altair可视化抖动图上的平均值?

时间:2020-06-13 05:21:32

标签: python altair

我需要获取每个大陆的平均值并将其绘制在抖动图上 刚刚找到了一个名为altair的很棒的库,我想绘制一个抖动图,就像我在下面找到的那样,但是我需要获取每个大陆的平均值并将其绘制在抖动图上。

开始我导入两个需要的库

import altair as alt
import pandas as pd

从源头获取数据

data_url = 'https://raw.githubusercontent.com/resbaz/r-novice-gapminder files/master/data/gapminder-FiveYearData.csv'

读取csv文件

gapminder = pd.read_csv(data_url)

从altair开始绘制

stripplot =  alt.Chart(gapminder).mark_circle(size=14).encode(
    x=alt.X(
        'jitter:Q',
        title=None,
        axis=alt.Axis(values=[0], ticks=True, grid=False, labels=False),
        scale=alt.Scale(),
    ),
    y=alt.Y('lifeExp:Q',
           scale=alt.Scale(
            domain=(20,90))),
    color=alt.Color('continent:N', legend=None),
    column=alt.Column(
        'continent:N',
        header=alt.Header(
            labelFontSize=16,
            labelAngle=0,
            titleOrient='top',
            labelOrient='bottom',
            labelAlign='center',
            labelPadding=25,
        ),
    ),
).transform_calculate(
    # Generate Gaussian jitter with a Box-Muller transform
    jitter='sqrt(-2*log(random()))*cos(2*PI*random())'
).configure_facet(
    spacing=0
).configure_view(
    stroke=None
).configure_axis(
    labelFontSize=16,
    titleFontSize=16
).properties(height=400, width=100)
stripplot

代码运行的很好,但我也不想显示每个大陆的平均值

2 个答案:

答案 0 :(得分:1)

在分面之前添加平均值,因为在制作分面表后无法进行分层。在 https://github.com/altair-viz/altair/issues/1158 上阅读更多内容,作者 jakevdp

stripplot =  alt.Chart(df, width=40).mark_point(size=8).encode(
    x=alt.X(
    'jitter:Q',
    title=None,
    axis=alt.Axis(values=[0], ticks=True, grid=False, labels=False),
    scale=alt.Scale(),
),
    y=alt.Y('lifeExp:Q'),
    color=alt.Color('continent:N', legend=None),
).transform_calculate(
# Generate Gaussian jitter with a Box-Muller transform
jitter='sqrt(-2*log(random()))*cos(2*PI*random())'
)
meanplot=alt.Chart(df, width=40).mark_tick(size=20).encode(
    y=alt.Y('mean(lifeExp):Q'),
    color=alt.Color('continent:N', legend=None),
)
fullplot=(meanplot+stripplot).facet(
    column=alt.Column(
        'continent:N',
        header=alt.Header(
            labelAngle=-90,
            titleOrient='top',
            labelOrient='bottom',
            labelAlign='right',
            labelPadding=3,
    ),

),
).configure_facet(
spacing=0
).configure_view(
stroke=None
)
fullplot

答案 1 :(得分:0)

我建议使用numpy库,它做到了:

import numpy as np

data = [15,50,30,40]
Print("Mean:",np.mean(data))

输出:

('mean:', 33.75)