python数据可视化1:单特征

作者: 章光辉_数据 | 来源:发表于2017-12-09 22:31 被阅读53次

    背景音乐:Summer Vibe - Walk off the Earth

    祝看到这篇文章的人,每天都有好心情✧(≖ ◡ ≖✿)

    1 概述

    数据可视化,从数据层面,包括以下两块内容:

    1. 单变量的可视化:主要研究变量的自身特性
    2. 多变量的联合可视化:主要研究变量与变量之间的相关性

    其中,单变量的可视化,要根据数据的类型来分别处理:

    1. 分类变量(categorical variable)
      常用的有:饼图、柱形图
    2. 数值变量(numerical variable)
      常用的有:概率密度图、直方图、箱式图

    回到标题本身,今天就来讲讲python的数据可视化。

    在python做数据分析的时候,有三个模块是绕不开的:pandasnumpy以及matplotlib

    同时,seaborn也是你可视化时必不可少的得力助手。

    写这个文章的目的,是对知识的一个梳理,也方便有需要的人能尽快上手。

    我会尽可能地用pandas、matplotlib和seaborn来共同实现上述可视化,同时为了代码简洁,我会尽量不进行没必要的设置。

    2 导入数据

    首先,导入必备的模块:

    %matplotlib inline
    import matplotlib.pyplot as plt
    import pandas as pd
    import numpy as np
    import seaborn as sns

    本次所用的数据来自kaggle竞赛的森林火灾面积预测

    df = pd.read_csv('forestfires.csv')
    df.head() # 看前5行

    数据内容

    3 分类特征

    分类特征主要看两个方面:

    1. 有几种分类
    2. 每种分类的数量(或者比例)

    这里为了演示,我用day变量,代表了星期

    order = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
    day_count = df['day'].value_counts()
    day_count = day_count[order] # 不用loc的话就默认从大到小排序
    day_count

    结果为

    mon 74
    tue 64
    wed 54
    thu 61
    fri 85
    sat 84
    sun 95
    Name: day, dtype: int64

    可以看到,数据集里这个变量的分布还算平均。

    3.1 饼图

    注意分类的种类不能太多,不然饼图就会被切得很细

    3.1.1 pandas.Series.plot.pie

    用autopct设置数字的格式

    day_count.plot.pie(autopct='%.2f%%')

    3.1.2 matplotlib.pyplot.pie

    plt.pie(day_count, autopct='%.2f%%', labels=day_count.index)

    3.2 柱状图

    3.2.1 pandas.Series.plot.pie

    day_count.plot.bar()

    3.2.2 matplotlib.pyplot.bar

    pos = range(len(day_count))
    plt.bar(pos, day_count.values)
    plt.xticks(pos, day_count.index)

    3.2.3 seaborn.barplot

    sns.barplot(day_count.index, day_count.values)

    3.2.4 seaborn.countplot

    用这个的好处在于,自动计算取值及其数量并可视化,节省一个步骤。
    函数中,可以设置order=order来指定顺序。

    sns.countplot(df['day'])

    4 数值特征

    数值特征主要看两个方面:

    1. 它的取值区间
    2. 不同子区间的数量分布(或者密度分布)

    为了演示,我用temp变量,代表温度

    temperature = df['temp']

    4.1 直方图

    4.1.1 pandas.Series.plot.hist

    temperature.plot.hist()

    4.1.2 matplotlib.pyplot.hist

    plt.hist(temperature)

    4.1.3 seaborn.rugplot

    这个是结合直方图使用的,能变得更好看

    plt.hist(temperature, color='orange')
    sns.rugplot(temperature)

    4.2 概率密度图

    4.2.1 pandas.Series.plot.density

    temperature.plot.density()

    4.2.2 seaborn.kdeplot

    sns.kdeplot(temperature)

    4.2.3 seaborn.distplot

    这个还结合了直方图,节省步骤
    函数中,可以设置hist=False来取消直方图

    sns.distplot(temperature)

    4.3 箱式图

    4.3.1 pandas.Series.plot.box

    temperature.plot.box()

    4.3.2 matplotlib.pyplot.boxplot

    plt.boxplot(temperature)
    plt.show()

    4.3.3 seaborn.boxplot

    orient默认值是h(水平),也可以设为v(垂直)

    sns.boxplot(temperature, orient='v')

    相关文章

      网友评论

        本文标题:python数据可视化1:单特征

        本文链接:https://www.haomeiwen.com/subject/gsujixtx.html