用 Python 绘制数据的7种最流行的方法( 三 )


Bokeh plot of British election data
AltairAltair 是基于一种名为 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')结果图表:

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

文章插图
 
Altair plot of British election data
PygalPygal 专注于视觉外观 。它默认生成 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')绘制结果:
用 Python 绘制数据的7种最流行的方法

文章插图
 
Pygal plot of British election data
PandasPandas 是 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()


推荐阅读