人不范二枉少年 发表于 2019-6-26 14:35:40

5个快速而简单的数据可视化方法和Python代码


导读

数据可视化的方法,做大数据的人不可错过,直接把代码喂给你。

数据可视化是数据科学家工作的重要组成部分。在项目的早期阶段,你通常会进行探索性数据分析(EDA),以获得对数据的一些见解。创建可视化确实有助于使事情更清晰和更容易理解,特别是对于更大的、高维的数据集。在项目接近尾声时,以一种清晰、简洁和引人注目的方式展示最终结果是非常重要的,这样你的受众(通常是非技术客户)就更加容易理解。

Matplotlib是一个流行的Python库,可以很容易地创建数据可视化。然而,每次执行新项目时,设置数据、参数、图形和绘图都会变得非常混乱和乏味。在这篇博客文章中,我们将研究5种数据可视化,并使用Python的Matplotlib为它们编写一些快速简单的函数。与此同时,这里有一个很棒的图表,可以帮助你为工作选择合适的可视化工具!

为给定的情况选择适当的数据可视化技术的图表

散点图
散点图非常适合显示两个变量之间的关系,因为你可以直接看到数据的原始分布。你还可以通过对组进行简单的颜色编码来查看不同组数据的这种关系,如下面的第一个图所示。想要可视化三个变量之间的关系吗?完全没有问题!只需使用另一个参数,如点大小,对第三个变量进行编码,如下面的图2所示。我们刚刚讨论的所有这些也与第一个图表一致。

用颜色分组的散点图

第三个变量,国家大小通过彩色分组和大小编码散点图

现在来看代码。我们首先使用别名“plt”导入Matplotlib的pyplot。为了创建一个新的plot图,我们将其称为“pl .subplot()”。我们将x轴和y轴数据传递给函数,然后将它们传递给“ax.scatter()”来绘制散点图。我们还可以设置点大小、点颜色和透明度。你甚至可以把y轴设成对数刻度。然后,为该图设置标题和轴标签。这是一个很容易使用的函数,它从头到尾创建了一个散点图!
import matplotlib.pyplot as plt
import numpy as np

def scatterplot(x_data, y_data, x_label="", y_label="", title="", color = "r", yscale_log=False):

    # Create the plot object
    _, ax = plt.subplots()

    # Plot the data, set the size (s), color and transparency (alpha)
    # of the points
    ax.scatter(x_data, y_data, s = 10, color = color, alpha = 0.75)

    if yscale_log == True:
      ax.set_yscale('log')

    # Label the axes and provide a title
    ax.set_title(title)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)

折线图
当你能清楚地看到一个变量随另一个变量的变化很大时,最好使用折线图。它们有高协方差。让我们看看下面的图来说明。我们可以清楚地看到,随着时间的推移,所有专业的百分比都有很大的变化。用散点图来画这些会非常混乱,很难理解和理解发生了什么。直线图非常适合这种情况,因为它们基本上可以快速总结为两个变量(百分比和时间)的协方差。同样,我们也可以使用颜色编码分组。从我们的第一个图表开始,折线图就属于“超时”类别。
折线图的例子

这是折线图的代码。这与上面的散点图非常相似。只有一些变量的小变化。
def lineplot(x_data, y_data, x_label="", y_label="", title=""):
    # Create the plot object
    _, ax = plt.subplots()

    # Plot the best fit line, set the linewidth (lw), color and
    # transparency (alpha) of the line
    ax.plot(x_data, y_data, lw = 2, color = '#539caf', alpha = 1)

    # Label the axes and provide a title
    ax.set_title(title)
    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)

直方图
直方图对于查看(或真正发现)数据点的分布非常有用。请查看下面的直方图,我们在其中绘制了频率直方图和IQ直方图。我们可以清楚地看到中心的浓度和中值。我们还可以看到它服从高斯分布。使用条形图(而不是散点图)可以让我们清楚地看到每个存储箱的频率之间的相对差异。使用箱子(离散化)真的帮助我们看到“大局”,如果我们使用没有离散箱子的所有数据点,在可视化中可能会有很多噪音,使我们很难看到真正发生了什么。

直方图的例子
Matplotlib中直方图的代码如下所示。有两个参数需要注意。首先,' n_boxes '参数控制我们需要多少个离散的箱子来制作我们的直方图。更多的箱子会给我们更好的信息,但也可能引入噪音,让我们远离大局,另一方面,更少的箱子给我们一个更“鸟瞰”和一个更大的画面,发生了什么,但是没有更详细的细节。其次,“累积”参数是一个布尔值,它允许我们选择直方图是否是累积的。这基本上是选择概率密度函数(PDF)或累积密度函数(CDF)。
def histogram(data, n_bins, cumulative=False, x_label = "", y_label = "", title = ""):
    _, ax = plt.subplots()
    ax.hist(data, n_bins = n_bins, cumulative = cumulative, color = '#539caf')
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)

假设我们要比较数据中两个变量的分布。有人可能会认为你需要制作两个单独的直方图,并将它们并排放在一起进行比较。但是,实际上有一种更好的方法:我们可以用不同的透明度覆盖直方图。看看下图。均匀分布的透明度设为0.5,这样我们就能看到它后面是什么。这允许直接在同一个图上查看这两个分布。

叠加直方图
对于叠加直方图,需要在代码中设置一些东西。首先,我们设置水平范围以适应这两个变量分布。根据这个范围和所需的箱子数量,我们实际上可以计算出每个箱子的宽度。最后,我们在同一块图上绘制两个直方图,其中一个稍微透明一些。
# Overlay 2 histograms to compare them
def overlaid_histogram(data1, data2, n_bins = 0, data1_name="", data1_color="#539caf", data2_name="", data2_color="#7663b0", x_label="", y_label="", title=""):
    # Set the bounds for the bins so that the two distributions are fairly compared
    max_nbins = 10
    data_range =
    binwidth = (data_range - data_range) / max_nbins


    if n_bins == 0
      bins = np.arange(data_range, data_range + binwidth, binwidth)
    else:
      bins = n_bins

    # Create the plot
    _, ax = plt.subplots()
    ax.hist(data1, bins = bins, color = data1_color, alpha = 1, label = data1_name)
    ax.hist(data2, bins = bins, color = data2_color, alpha = 0.75, label = data2_name)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
    ax.legend(loc = 'best')

条形图
当你试图可视化分类数据,有几个(可能小于10)类别,这时,条形图是最有效的。如果我们有太多的类别,那么这些条形图会非常混乱,难以理解。它们非常适合分类数据,因为你可以很容易地通过条形图大小看到类别之间的差异。类别也很容易通过颜色编码来划分。我们将看到三种不同类型的条形图:常规条形图、分组条形图和堆叠条形图。在我们进行的过程中,请查看下图中的代码。

常规的条形图如下面的第一个图所示。在' barplot() '函数中,' xdata '表示x轴上的标记,' ydata '表示y轴上的条高。误差条是以每个栏为中心的一条额外的线,用来显示标准差。

分组条形图允许我们比较多个分类变量。查看下面的第二个条形图。我们要比较的第一个变量是各组得分的变化情况。我们还将性别本身与颜色编码进行了比较。看一下代码,' ydatalist '变量现在实际上是列表的列表,其中每个子列表表示不同的组。然后我们循环遍历每一组,对于每一组,我们在x轴上画出每一个刻度的横杠,每一组也用颜色进行编码。

堆叠的条形图对于可视化不同变量的分类构成非常有用。在下面的堆叠条形图中,我们比较了每天的服务器负载。通过使用颜色编码,我们可以很容易地看到和理解哪些服务器每天的工作量最大,以及负载与其他服务器的负载相比如何。其代码遵循与分组条形图相同的样式。我们循环遍历每一组,但是这次我们在旧的条形图上绘图,而不是在它们旁边画新条形图。

常规条形图

分组条形图

堆叠条形图
def barplot(x_data, y_data, error_data, x_label="", y_label="", title=""):
    _, ax = plt.subplots()
    # Draw bars, position them in the center of the tick mark on the x-axis
    ax.bar(x_data, y_data, color = '#539caf', align = 'center')
    # Draw error bars to show standard deviation, set ls to 'none'
    # to remove line between points
    ax.errorbar(x_data, y_data, yerr = error_data, color = '#297083', ls = 'none', lw = 2, capthick = 2)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)



def stackedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""):
    _, ax = plt.subplots()
    # Draw bars, one category at a time
    for i in range(0, len(y_data_list)):
      if i == 0:
            ax.bar(x_data, y_data_list, color = colors, align = 'center', label = y_data_names)
      else:
            # For each category after the first, the bottom of the
            # bar will be the top of the last category
            ax.bar(x_data, y_data_list, color = colors, bottom = y_data_list, align = 'center', label = y_data_names)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
    ax.legend(loc = 'upper right')



def groupedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""):
    _, ax = plt.subplots()
    # Total width for all bars at one x location
    total_width = 0.8
    # Width of each individual bar
    ind_width = total_width / len(y_data_list)
    # This centers each cluster of bars about the x tick mark
    alteration = np.arange(-(total_width/2), total_width/2, ind_width)

    # Draw bars, one category at a time
    for i in range(0, len(y_data_list)):
      # Move the bar to the right on the x-axis so it doesn't
      # overlap with previously drawn ones
      ax.bar(x_data + alteration, y_data_list, color = colors, label = y_data_names, width = ind_width)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)
    ax.legend(loc = 'upper right')


箱线图
我们之前研究过直方图它很好地可视化了变量的分布。但如果我们需要更多的信息呢?也许我们想更清楚地了解标准差?也许中值和均值有很大不同,所以有很多离群值?如果有这么大的歪斜,而且很多值都集中在一边呢?

这就是箱线图的作用。箱线图给出了上面所有的信息。实线盒的底部和顶部总是第一和第三四分位数(25%和75%的数据),而框内的带始终是第二四分位数(中位数)。虚线加上最后的条,从框中延伸出来显示数据的范围。

由于每个组/变量都绘制了箱线图,所以设置起来非常简单。' xdata '是组/变量的列表。Matplotlib函数' boxplot() '为' ydata '的每一列或序列' ydata '中的每个向量绘制一个箱线图,因此,“xdata”中的每个值对应于“y_data”中的列/向量。

箱线图的例子
def boxplot(x_data, y_data, base_color="#539caf", median_color="#297083", x_label="", y_label="", title=""):
    _, ax = plt.subplots()

    # Draw boxplots, specifying desired style
    ax.boxplot(y_data
               # patch_artist must be True to control box fill
               , patch_artist = True
               # Properties of median line
               , medianprops = {'color': median_color}
               # Properties of box
               , boxprops = {'color': base_color, 'facecolor': base_color}
               # Properties of whiskers
               , whiskerprops = {'color': base_color}
               # Properties of whisker caps
               , capprops = {'color': base_color})

    # By default, the tick label starts at 1 and increments by 1 for
    # each box drawn. This sets the labels to the ones we want
    ax.set_xticklabels(x_data)
    ax.set_ylabel(y_label)
    ax.set_xlabel(x_label)
    ax.set_title(title)

总结
这里有5个使用Matplotlib的快速和简单的数据可视化。把东西抽象成函数总是让你的代码更容易阅读和使用!

页: [1]
查看完整版本: 5个快速而简单的数据可视化方法和Python代码