Python 中绘制数据的 7 种最流行方法

比较七个用于在 Python 中绘图的库和 API,看看哪个最适合您的需求。
156 位读者喜欢这个。
wavegraph

Opensource.com

“如何在 Python 中绘图?” 曾经有一个简单的答案:Matplotlib 是唯一的方法。如今,Python 是 数据科学 的语言,并且有更多选择。您应该使用什么?

本指南将帮助您做出决定。它将向您展示如何使用四个最流行的 Python 绘图库——MatplotlibSeabornPlotlyBokeh——以及另外几个值得考虑的后起之秀:Altair,及其富有表现力的 API,以及 Pygal,及其精美的 SVG 输出。我还将介绍 pandas 提供的非常方便的绘图 API。

对于每个库,我都包含了源代码片段,以及使用 Anvil(我们仅使用 Python 构建 Web 应用程序的平台)的完整基于 Web 的示例。让我们来看看。

示例图

每个库都采用略有不同的方法来绘制数据。为了比较它们,我将使用每个库制作相同的图表,并向您展示源代码。对于我的示例数据,我选择了自 1966 年以来英国选举结果的分组条形图

Bar chart of British election data

我从维基百科汇编了 英国选举历史数据集:从 1966 年到 2019 年的每次选举中,保守党、工党和自由党(广义上定义)赢得的英国议会席位数,以及“其他”党派赢得的席位数。您可以 将其下载为 CSV 文件

Matplotlib

Matplotlib 是最古老的 Python 绘图库,并且仍然是最流行的。它于 2003 年创建,是 SciPy Stack(类似于 Matlab 的开源科学计算库)的一部分。

Matplotlib 使您可以精确控制绘图——例如,您可以定义条形图中每个条形的单独 x 位置。这是绘制此图的代码(您可以在 此处 运行)

    import matplotlib.pyplot as plt
    import numpy as np
    from votes import wide as df

    # Initialise a figure. subplots() with no args gives one plot.
    fig, ax = plt.subplots()

    # A little data preparation
    years = df['year']
    x = np.arange(len(years))

    # Plot each bar plot. Note: manually calculating the 'dodges' of the bars
    ax.bar(x - 3*width/2, df['conservative'], width, label='Conservative', color='#0343df')
    ax.bar(x - width/2, df['labour'], width, label='Labour', color='#e50000')
    ax.bar(x + width/2, df['liberal'], width, label='Liberal', color='#ffff14')
    ax.bar(x + 3*width/2, df['others'], width, label='Others', color='#929591')

    # Customise some display properties
    ax.set_ylabel('Seats')
    ax.set_title('UK election results')
    ax.set_xticks(x)    # This ensures we have one tick per year, otherwise we get fewer
    ax.set_xticklabels(years.astype(str).values, rotation='vertical')
    ax.legend()

    # Ask Matplotlib to show the plot
    plt.show()

这是在 Matplotlib 中绘制的选举结果

Matplotlib plot of British election data

 

Seaborn

Seaborn 是 Matplotlib 之上的一个抽象层;它为您提供了一个非常简洁的界面,可以非常轻松地制作各种有用的绘图类型。

但这并没有牺牲功能!Seaborn 提供了 逃生舱口 来访问底层的 Matplotlib 对象,因此您仍然拥有完全的控制权。

Seaborn 的代码比原始 Matplotlib 更简单(可在 此处 运行)

    import seaborn as sns
    from votes import long as df

    # Some boilerplate to initialise things
    sns.set()
    plt.figure()

    # This is where the actual plot gets made
    ax = sns.barplot(data=df, x="year", y="seats", hue="party", palette=['blue', 'red', 'yellow', 'grey'], saturation=0.6)

    # Customise some display properties
    ax.set_title('UK election results')
    ax.grid(color='#cccccc')
    ax.set_ylabel('Seats')
    ax.set_xlabel(None)
    ax.set_xticklabels(df["year"].unique().astype(str), rotation='vertical')

    # Ask Matplotlib to show it
    plt.show()

并生成此图表

Seaborn plot of British election data

Plotly

Plotly 是一个绘图生态系统,其中包括一个 Python 绘图库。它有三个不同的界面

  • 面向对象的界面
  • 允许您使用类似 JSON 的数据结构指定绘图的命令式界面
  • 类似于 Seaborn 的高级界面,称为 Plotly Express

Plotly 图表旨在嵌入到 Web 应用程序中。Plotly 的核心实际上是一个 JavaScript 库!它使用 D3stack.gl 绘制图表。

您可以通过将 JSON 传递给 JavaScript 库来构建其他语言的 Plotly 库。官方的 Python 和 R 库就是这样做的。在 Anvil,我们将 Python Plotly API 移植到 在 Web 浏览器中运行

这是 Plotly 中的源代码(您可以在 此处 运行)

    import plotly.graph_objects as go
    from votes import wide as df

    #  Get a convenient list of x-values
    years = df['year']
    x = list(range(len(years)))

    # Specify the plots
    bar_plots = [
        go.Bar(x=x, y=df['conservative'], name='Conservative', marker=go.bar.Marker(color='#0343df')),
        go.Bar(x=x, y=df['labour'], name='Labour', marker=go.bar.Marker(color='#e50000')),
        go.Bar(x=x, y=df['liberal'], name='Liberal', marker=go.bar.Marker(color='#ffff14')),
        go.Bar(x=x, y=df['others'], name='Others', marker=go.bar.Marker(color='#929591')),
    ]

    # Customise some display properties
    layout = go.Layout(
        title=go.layout.Title(text="Election results", x=0.5),
        yaxis_title="Seats",
        xaxis_tickmode="array",
        xaxis_tickvals=list(range(27)),
        xaxis_ticktext=tuple(df['year'].values),
    )

    # Make the multi-bar plot
    fig = go.Figure(data=bar_plots, layout=layout)

    # Tell Plotly to render it
    fig.show()

以及选举结果图

Plotly plot of British election data

Bokeh

Bokeh(发音为“BOE-kay”)专门构建交互式图表,因此这个标准示例并没有充分展示其优势。与 Plotly 类似,Bokeh 的图表旨在嵌入到 Web 应用程序中;它将其图表输出为 HTML 文件。

这是 Bokeh 中的代码(您可以在 此处 运行)

    from bokeh.io import show, output_file
    from bokeh.models import ColumnDataSource, FactorRange, HoverTool
    from bokeh.plotting import figure
    from bokeh.transform import factor_cmap
    from votes import long as df

    # Specify a file to write the plot to
    output_file("elections.html")

    # Tuples of groups (year, party)
    x = [(str(r[1]['year']), r[1]['party']) for r in df.iterrows()]
    y = df['seats']

    # Bokeh wraps your data in its own objects to support interactivity
    source = ColumnDataSource(data=dict(x=x, y=y))

    # Create a colourmap
    cmap = {
        'Conservative': '#0343df',
        'Labour': '#e50000',
        'Liberal': '#ffff14',
        'Others': '#929591',
    }
    fill_color = factor_cmap('x', palette=list(cmap.values()), factors=list(cmap.keys()), start=1, end=2)

    # Make the plot
    p = figure(x_range=FactorRange(*x), width=1200, title="Election results")
    p.vbar(x='x', top='y', width=0.9, source=source, fill_color=fill_color, line_color=fill_color)

    # Customise some display properties
    p.y_range.start = 0
    p.x_range.range_padding = 0.1
    p.yaxis.axis_label = 'Seats'
    p.xaxis.major_label_orientation = 1
    p.xgrid.grid_line_color = None

以及图表

Bokeh plot of British election data

Altair

Altair 基于一种声明式绘图语言(或“可视化语法”),称为 Vega。这意味着它是一个经过深思熟虑的 API,可以很好地扩展到复杂的绘图,使您免于迷失在嵌套循环的炼狱中。

与 Bokeh 一样,Altair 将其图表输出为 HTML 文件。这是代码(您可以在 此处 运行)

    import altair as alt
    from votes import long as df

    # Set up the colourmap
    cmap = {
        'Conservative': '#0343df',
        'Labour': '#e50000',
        'Liberal': '#ffff14',
        'Others': '#929591',
    }

    # Cast years to strings
    df['year'] = df['year'].astype(str)

    # Here's where we make the plot
    chart = alt.Chart(df).mark_bar().encode(
        x=alt.X('party', title=None),
        y='seats',
        column=alt.Column('year', sort=list(df['year']), title=None),
        color=alt.Color('party', scale=alt.Scale(domain=list(cmap.keys()), range=list(cmap.values())))
    )

    # Save it as an HTML file.
    chart.save('altair-elections.html')

以及生成的图表

Altair plot of British election data

Pygal

Pygal 专注于视觉外观。默认情况下,它生成 SVG 图表,因此您可以永久缩放它们或打印它们而不会使它们像素化。Pygal 图表还带有一些内置的良好交互功能,如果您希望将图表嵌入到 Web 应用程序中,Pygal 是另一个被低估的候选者。

源代码如下所示(您可以在 此处 运行它)

    import pygal
    from pygal.style import Style
    from votes import wide as df

    # Define the style
    custom_style = Style(
        colors=('#0343df', '#e50000', '#ffff14', '#929591')
        font_family='Roboto,Helvetica,Arial,sans-serif',
        background='transparent',
        label_font_size=14,
    )

    # Set up the bar plot, ready for data
    c = pygal.Bar(
        title="UK Election Results",
        style=custom_style,
        y_title='Seats',
        width=1200,
        x_label_rotation=270,
    )

    # Add four data sets to the bar plot
    c.add('Conservative', df['conservative'])
    c.add('Labour', df['labour'])
    c.add('Liberal', df['liberal'])
    c.add('Others', df['others'])

    # Define the X-labels
    c.x_labels = df['year']

    # Write this to an SVG file
    c.render_to_file('pygal.svg')

以及图表

Pygal plot of British election data

Pandas

Pandas 是一个非常流行的 Python 数据科学库。它允许您可扩展地进行各种数据操作,但它也具有方便的绘图 API。由于它直接在数据帧上运行,因此 pandas 示例是本文中最简洁的代码片段——甚至比 Seaborn 代码还要短!

pandas API 是 Matplotlib 的包装器,因此您也可以使用底层的 Matplotlib API 来精细控制您的绘图。

这是 pandas 中的选举结果图。代码非常简洁!

    from matplotlib.colors import ListedColormap
    from votes import wide as df

    cmap = ListedColormap(['#0343df', '#e50000', '#ffff14', '#929591'])

    ax = df.plot.bar(x='year', colormap=cmap)

    ax.set_xlabel(None)
    ax.set_ylabel('Seats')
    ax.set_title('UK election results')

    plt.show()

以及生成的图表

Pandas plot of British election data

要运行此示例,请查看 此处

绘制您的方式

Python 提供了许多方法来绘制相同的数据,而无需太多代码。虽然您可以使用这些方法中的任何一种快速开始创建图表,但它们确实需要一些本地配置。Anvil 为需要 Python 开发的您提供精美的基于 Web 的体验。祝您绘图愉快!


本文基于 Anvil 博客上的 Python 绘图:比较各种选项,并经许可重复使用。

接下来阅读什么
User profile image.
Shaun 最初认真编程是通过模拟世界最大激光系统中的燃烧聚变等离子体开始的。他爱上了 Python 作为数据分析工具,并且再也没有回头。现在他想把一切都变成 Python。

5 条评论

感谢链接!您是对的,对于这些特定数据,四个叠加的折线图会更易读。就我个人而言,条形图给我带来的快乐很少……但我选择多条形示例是因为它可以很好地梳理出不同库之间的差异。

回复 作者 Greg P

非常感谢您的辛勤付出

很棒的文章!谢谢。

像这样的比较真的很有趣,并突出了相似之处和不同之处。
我个人一直使用 matplotlib,但我肯定会看看其他库。

这些真的很棒!我已经使用 Matplotlib 一段时间了,它真的很好,但我一定会尝试其他库。谢谢!

Creative Commons License本作品根据 Creative Commons Attribution-Share Alike 4.0 International License 获得许可。
© . All rights reserved.