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

并生成这样的图表:

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

文章插图
 
Seaborn plot of British election data
PlotlyPlotly 是一个绘图生态系统 , 它包括一个 Python 绘图库 。它有三个不同的接口:
  1. 一个面向对象的接口 。
  2. 一个命令式接口 , 允许你使用类似 JSON 的数据结构来指定你的绘图 。
  3. 类似于 Seaborn 的高级接口 , 称为 Plotly Express 。
Plotly 绘图被设计成嵌入到 Web 应用程序中 。Plotly 的核心其实是一个 JAVAScript 库!它使用 D3 和 stack.gl 来绘制图表 。
你可以通过向该 JavaScript 库传递 JSON 来构建其他语言的 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=https://www.isolves.com/it/cxkf/yy/Python/2020-07-09/bar_plots, layout=layout) # Tell Plotly to render it fig.show()选举结果图表:
用 Python 绘制数据的7种最流行的方法

文章插图
 
Plotly plot of British election data
BokehBokeh (发音为 “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=https://www.isolves.com/it/cxkf/yy/Python/2020-07-09/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图表如下:
 
用 Python 绘制数据的7种最流行的方法

文章插图
 


推荐阅读