📜  如何使用 Altair 在Python中绘制密度图?

📅  最后修改于: 2022-05-13 01:55:18.276000             🧑  作者: Mango

如何使用 Altair 在Python中绘制密度图?

密度图是直方图的一种变体,用于观察数据集中变量在连续间隔或时间段内的分布。密度图的峰值指示值在某个区间内的集中位置。

与直方图相比,密度图更擅长确定分布形状,因为它们不受 bin 数量的影响。

使用 Altair 在Python中绘制密度图

我们可以使用 Pandas 和 Altair 库在Python中制作密度图。

  • Altair-It 是一个基于 Vega 和 Vega-lite 的统计可视化库。
  • Pandas-It 是一个开源的Python数据分析和操作工具。

注意:我们将使用可从 Google Drive 下载的“insurance.csv”数据集。

首先,让我们使用-导入这些库

Python3
import pandas as p  # loading pandas library
import altair as a  # loading altair library


Python3
data_set = 'insurance.csv'  # dataset name
d = p.read_csv(data_set)  # reading the datasaet
d.head()  # printing the first 5 data entries


Python3
# loading a single column into
# the data frame object
d = d[["charges"]]
 
a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'],
                             ).mark_area(color='green').encode(
    x="CHARGES:Q",
    y='DENSITY:Q',
 
)


Python3
import pandas as p  # loading pandas library
import altair as a  # loading altair library
 
# download dataset from https://drive.google.com/drive/folders/1Dddv1l9hpEPVWh_uuK9Iv1A1xUNy55v7?usp=sharing
# OR replace name with your own dataset.
data_set = 'insurance.csv'
d = p.read_csv(data_set)
d = d[["charges"]]
 
a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'],
                             ).mark_area(color='green').encode(
    x="CHARGES:Q",
    y='DENSITY:Q',
)


接下来,我们加载需要使用密度图的数据集。

蟒蛇3

data_set = 'insurance.csv'  # dataset name
d = p.read_csv(data_set)  # reading the datasaet
d.head()  # printing the first 5 data entries

输出:

如您所见,数据集中有七列。我们将使用“电荷”来绘制密度图。为此,我们必须首先将数据转换为密度。这是通过使用 transform_density()函数来完成的。参数是感兴趣的变量和一个名称,以表示转换后的变量,写为“as_=['Charges', 'density']”。把它放在一起——

蟒蛇3

# loading a single column into
# the data frame object
d = d[["charges"]]
 
a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'],
                             ).mark_area(color='green').encode(
    x="CHARGES:Q",
    y='DENSITY:Q',
 
)

输出:

输出

完整脚本:这是所有步骤集中在一处的代码-

蟒蛇3

import pandas as p  # loading pandas library
import altair as a  # loading altair library
 
# download dataset from https://drive.google.com/drive/folders/1Dddv1l9hpEPVWh_uuK9Iv1A1xUNy55v7?usp=sharing
# OR replace name with your own dataset.
data_set = 'insurance.csv'
d = p.read_csv(data_set)
d = d[["charges"]]
 
a.Chart(d).transform_density('charges', as_=['CHARGES', 'DENSITY'],
                             ).mark_area(color='green').encode(
    x="CHARGES:Q",
    y='DENSITY:Q',
)

输出:

输出