美文网首页大数据 爬虫Python AI Sql互联网科技程序员
5个案例教你用Python玩转数据可视化

5个案例教你用Python玩转数据可视化

作者: 919b0c54458f | 来源:发表于2019-04-06 15:16 被阅读10次

    1、选择Seaborn的调色板

    Seaborn的调色板和matplotlib的颜色表类似。色彩可以帮助你发现数据中的模式,也是重要的可视化组成部分。Seaborn有很丰富的调色板,在这个示例中会将其可视化。

    操作步骤

    (1)导入部分如下:

    import seaborn as sns
    
    import matplotlib.pyplot as plt
    
    import matplotlib as mpl
    
    import numpy as np
    
    from dautil import plotting
    

    (2)使用以下函数帮助绘制调色板:

    def plot_palette(ax, plotter, pal, i, label, ncol=1):
    
    n = len(pal)
    
    x = np.linspace(0.0, 1.0, n)
    
    y = np.arange(n) + i*n
    
    ax.scatter(x, y, c=x,
    
    cmap=mpl.colors.ListedColormap(list(pal)),
    
    s=200)
    
    plotter.plot(x,y,label=label)
    
    handles, labels = ax.get_legend_handles_labels()
    
    ax.legend(loc='best', ncol=ncol, fontsize=18)
    

    (3)分类调色板(categorical palette)对于分类数据很有用,例如性别、血型等。以下函数可以绘制一些Seaborn的分类调色板:

    def plot_categorical_palettes(ax):
    
    palettes = ['deep', 'muted', 'pastel', 'bright', 'dark','colorblind']
    
    plotter = plotting.CyclePlotter(ax)
    
    ax.set_title('Categorical Palettes')
    
    for i, p in enumerate(palettes):
    
    pal = sns.color_palette(p)
    
    plot_palette(ax, plotter, pal, i, p, 4)
    

    (4)圆形色彩系统(circular color system)通常用HLS(色度亮度饱和度,Hue Lightness Saturation)来取代RGB(红绿蓝Red Gree Blue)颜色空间。如果你有很多分类这将会很有用。以下函数可以使用HLS系统绘制调色板。

    def plot_circular_palettes(ax):
    
    ax.set_title('Circular Palettes')
    
    plotter = plotting.CyclePlotter(ax)
    
    pal = sns.color_palette("hls", 6)
    
    plot_palette(ax, plotter, pal, 0, 'hls')
    
    sns.hls_palette(6, l=.3, s=.8)
    
    plot_palette(ax, plotter, pal, 1, 'hls l=.3 s=.8')
    
    pal = sns.color_palette("husl", 6)
    
    plot_palette(ax, plotter, pal, 2, 'husl')
    
    sns.husl_palette(6, l=.3, s=.8)
    
    plot_palette(ax, plotter, pal, 3, 'husl l=.3 s=.8')
    

    (5)Seaborn也有基于在线的ColorBrewer工具的调色板(http://colorbrewer2.org/)。用以下函数绘制出来:

    def plot_brewer_palettes(ax):
    
    ax.set_title('Brewer Palettes')
    
    plotter = plotting.CyclePlotter(ax)
    
    pal = sns.color_palette("Paired")
    
    plot_palette(ax, plotter, pal, 0, 'Paired')
    
    pal = sns.color_palette("Set2", 6)
    
    plot_palette(ax, plotter, pal, 1, 'Set2')
    

    (6)连续调色板(sequential palettes)对于数据范围很广的数据来说很有用,比如说有数量级差异的数据。用以下函数绘制出来:

    def plot_sequential_palettes(ax):
    
    ax.set_title('Sequential Palettes')
    
    plotter = plotting.CyclePlotter(ax)
    
    pal = sns.color_palette("Blues")
    
    plot_palette(ax, plotter, pal, 0, 'Blues')
    
    pal = sns.color_palette("BuGn_r")
    
    plot_palette(ax, plotter, pal, 1, 'BuGn_r')
    
    pal = sns.color_palette("GnBu_d")
    
    plot_palette(ax, plotter, pal, 2, 'GnBu_d')
    
    pal = sns.color_palette("cubehelix", 6)
    
    plot_palette(ax, plotter, pal, 3, 'cubehelix')
    

    (7)以下几行代码调用了我们之前定义的函数:

    %matplotlib inline
    
    fig, axes = plt.subplots(2, 2, figsize=(16, 12))
    
    plot_categorical_palettes(axes[0][0])
    
    plot_circular_palettes(axes[0][1])
    
    plot_brewer_palettes(axes[1][0])
    
    plot_sequential_palettes(axes[1][1])
    
    plotting.hide_axes(axes)
    
    plt.tight_layout()
    

    请参见以下截图了解最终结果:

    image

    2、选择matplotlib的颜色表

    matplotlib的颜色表最近受到了很多批评,因为它们可能会误导用户,但是在我看来大多数的颜色表还是不错的。默认的颜色表在matplotlib 2.0中有一些改进,可以在这里查看:

    http://matplotlib.org/style_changes.html

    当然,有些matplotlib的颜色表不支持一些不错的参数,比如说jet。在艺术中,就像数据分析中一样,几乎没有什么东西是绝对正确的,所以这里就交给读者去判断。

    实际上,我觉得考虑如何解决印刷出版物以及各种各样的色盲问题是很重要的。在这个示例中我将用色条来可视化相对安全的颜色表。这里使用到的是matplotlib众多颜色表中的很小一部分。

    操作步骤

    (1)导入部分如下:

    import matplotlib.pyplot as plt
    
    import matplotlib as mpl
    
    from dautil import plotting
    

    (2)通过以下代码画出数据集:

    fig, axes = plt.subplots(4, 4)
    
    cmaps = ['autumn', 'spring', 'summer', 'winter',
    
    'Reds', 'Blues', 'Greens', 'Purples',
    
    'Oranges', 'pink', 'Greys', 'gray',
    
    'binary', 'bone', 'hot', 'cool']
    
    for ax, cm in zip(axes.ravel(), cmaps):
    
    cmap = plt.cm.get_cmap(cm)
    
    cb = mpl.colorbar.ColorbarBase(ax, cmap=cmap,
    
    orientation='horizontal')
    
    cb.set_label(cm)
    
    ax.xaxis.set_ticklabels([])
    
    plt.tight_layout()
    
    plt.show()
    

    请参见以下截图了解最终结果:

    image

    3、查看散点图矩阵

    如果你的数据集中变量不是很多,那么查看你数据所有的散点图是个不错的主意。通过调用Seaborn或者pandas的一个函数就可以做到。这些函数会展示一个矩阵的核密度估计图或对角线上的直方图。

    Python学习群:556370268,有大牛答疑,有资源共享!是一个非常不错的交流基地!欢迎喜欢Python的小伙伴!

    操作步骤

    (1)导入部分如下:

    import pandas as pd
    
    from dautil import data
    
    from dautil import ts
    
    import matplotlib.pyplot as plt
    
    import seaborn as sns
    
    import matplotlib as mpl
    

    (2)以下几行代码加载天气数据:

    df = data.Weather.load()
    
    df = ts.groupby_yday(df).mean()
    
    df.columns = [data.Weather.get_header(c) for c in df.columns]
    

    (3)用Seaborn的pairplot()函数绘制图形,这个函数默认绘制对角线上的直方图:

    %matplotlib inline
    
    # Seaborn plotting, issues due to NaNs
    
    sns.pairplot(df.fillna(0))
    

    结果如下所示:

    image

    (4)通过pandas的scatter_matrix()函数生成一个类似的图形,并请求对角线上的核密度估计图:

    sns.set({'figure.figsize': '16, 12'})
    
    mpl.rcParams['axes.linewidth'] = 9
    
    mpl.rcParams['lines.linewidth'] = 2
    
    plots = pd.scatter_matrix(df, marker='o', diagonal='kde')
    
    plt.show()
    

    请参见以下截图了解最终结果:

    image

    4、通过mpld3使用d3.js进行可视化

    d3.js是在2011年推出的一个JavaScript数据可视化库,我们可以在IPython Notebook里面使用这个库。我们将在一个普通matplotlib图上添加一个悬浮工具提示。这里我们会使用mpld3包作为使用d3.js的桥梁。这个示例不需要任何JavaScript编程。

    1. 准备工作

    通过以下命令安装mpld3 0.2:

    $ [sudo] pip install mpld3

    2. 操作步骤

    (1)由导入开始,并启用mpld3:

    %matplotlib inline
    
    import matplotlib.pyplot as plt
    
    import mpld3
    
    mpld3.enable_notebook()
    
    from mpld3 import plugins
    
    import seaborn as sns
    
    from dautil import data
    
    from dautil import ts
    

    (2)加载天气数据并按照下面的方法将其绘制出来:

    df = data.Weather.load()
    
    df = df[['TEMP', 'WIND_SPEED']]
    
    df = ts.groupby_yday(df).mean()
    
    fig, ax = plt.subplots()
    
    ax.set_title('Averages Grouped by Day of Year')
    
    points = ax.scatter(df['TEMP'], df['WIND_SPEED'],
    
    s=30, alpha=0.3)
    
    ax.set_xlabel(data.Weather.get_header('TEMP'))
    
    ax.set_ylabel(data.Weather.get_header('WIND_SPEED'))
    
    labels = ["Day of year ".format(i) for i in range(366)]
    
    tooltip = plugins.PointLabelTooltip(points, labels)
    
    plugins.connect(fig, tooltip)
    

    高亮显示的那一行是工具栏。在下面的截图中,我们可以看到“Day of year 31”文本来自这个工具栏:

    image

    如你所见,在这个图形的底部,还有可以平移和缩放图形的装置。

    5、把箱线图、核密度图和小提琴图组合

    小提琴图(Violin Plot)是一种组合盒图和核密度图或直方图的图形类型。Seaborn和matplotlib都能提供小提琴图。在这个示例中我们将使用Seaborn来绘制天气数据的Z分数(标准分数),分数的标准化并不是必需的,但是如果没有它的话小提琴图会很发散。

    Python学习群:556370268,有大牛答疑,有资源共享!是一个非常不错的交流基地!欢迎喜欢Python的小伙伴!

    操作步骤

    (1)导入部分如下:

    import seaborn as sns
    
    from dautil import data
    
    import matplotlib.pyplot as plt
    

    (2)加载天气数据并计算标准分数:

    df = data.Weather.load()
    
    zscores = (df - df.mean())/df.std()
    

    (3)绘制标准分数的小提琴图:

    %matplotlib inline
    
    plt.figure()
    
    plt.title('Weather Violin Plot')
    
    sns.violinplot(zscores.resample('M').mean())
    
    plt.ylabel('Z-scores')
    

    第一个小提琴图如下所示:

    image

    (4)绘制雨天和旱天相对风速的小提琴图:

    plt.figure()
    
    plt.title('Rainy Weather vs Wind Speed')
    
    categorical = df
    
    categorical['RAIN'] = categorical['RAIN'] > 0
    
    ax = sns.violinplot(x="RAIN", y="WIND_SPEED",data=categorical)
    

    第二个小提琴图如下所示:

    image

    相关文章

      网友评论

        本文标题:5个案例教你用Python玩转数据可视化

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