成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

用 Python 繪制數(shù)據(jù)的7種流行的方法

開(kāi)發(fā) 后端
本篇文章比較七個(gè)在 Python 中繪圖的庫(kù)和 API,看看哪個(gè)最能滿(mǎn)足你的需求。

“如何在 Python 中繪圖?”曾經(jīng)這個(gè)問(wèn)題有一個(gè)簡(jiǎn)單的答案:Matplotlib 是唯一的辦法。如今,Python 作為數(shù)據(jù)科學(xué)的語(yǔ)言,有著更多的選擇。你應(yīng)該用什么呢?

本指南將幫助你決定。

它將向你展示如何使用四個(gè)最流行的 Python 繪圖庫(kù):Matplotlib、Seaborn、Plotly 和 Bokeh,再加上兩個(gè)值得考慮的優(yōu)秀的后起之秀:Altair,擁有豐富的 API;Pygal,擁有漂亮的 SVG 輸出。我還會(huì)看看 Pandas 提供的非常方便的繪圖 API。

對(duì)于每一個(gè)庫(kù),我都包含了源代碼片段,以及一個(gè)使用 Anvil 的完整的基于 Web 的例子。Anvil 是我們的平臺(tái),除了 Python 之外,什么都不用做就可以構(gòu)建網(wǎng)絡(luò)應(yīng)用。讓我們一起來(lái)看看。

示例繪圖

每個(gè)庫(kù)都采取了稍微不同的方法來(lái)繪制數(shù)據(jù)。為了比較它們,我將用每個(gè)庫(kù)繪制同樣的圖,并給你展示源代碼。對(duì)于示例數(shù)據(jù),我選擇了這張 1966 年以來(lái)英國(guó)大選結(jié)果的分組柱狀圖。

Bar chart of British election data我從維基百科上整理了英國(guó)選舉史的數(shù)據(jù)集:從 1966 年到 2019 年,保守黨、工黨和自由黨(廣義)在每次選舉中贏得的英國(guó)議會(huì)席位數(shù),加上“其他”贏得的席位數(shù)。你可以以 CSV 文件格式下載它。

Matplotlib

Matplotlib 是最古老的 Python 繪圖庫(kù),現(xiàn)在仍然是最流行的。它創(chuàng)建于 2003 年,是 SciPy Stack 的一部分,SciPy Stack 是一個(gè)類(lèi)似于 Matlab 的開(kāi)源科學(xué)計(jì)算庫(kù)。

Matplotlib 為你提供了對(duì)繪制的精確控制。例如,你可以在你的條形圖中定義每個(gè)條形圖的單獨(dú)的 X 位置。下面是繪制這個(gè)圖表的代碼(你可以在這里運(yùn)行):

  1. import matplotlib.pyplot as plt 
  2.    import numpy as np 
  3.    from votes import wide as df 
  4.    # Initialise a figure. subplots() with no args gives one plot. 
  5.    fig, ax = plt.subplots() 
  6.    # A little data preparation 
  7.    years = df['year'] 
  8.    x = np.arange(len(years)) 
  9.    # Plot each bar plot. Note: manually calculating the 'dodges' of the bars 
  10.    ax.bar(x - 3*width/2, df['conservative'], width, label='Conservative'color='#0343df'
  11.    ax.bar(x - width/2, df['labour'], width, label='Labour'color='#e50000'
  12.    ax.bar(x + width/2, df['liberal'], width, label='Liberal'color='#ffff14'
  13.    ax.bar(x + 3*width/2, df['others'], width, label='Others'color='#929591'
  14.    # Customise some display properties 
  15.    ax.set_ylabel('Seats') 
  16.    ax.set_title('UK election results') 
  17.    ax.set_xticks(x)    # This ensures we have one tick per year, otherwise we get fewer 
  18.    ax.set_xticklabels(years.astype(str).values, rotation='vertical'
  19.    ax.legend() 
  20.    # Ask Matplotlib to show the plot 
  21.    plt.show() 

這是用 Matplotlib 繪制的選舉結(jié)果:

Matplotlib plot of British election data

Seaborn

Seaborn 是 Matplotlib 之上的一個(gè)抽象層;它提供了一個(gè)非常整潔的界面,讓你可以非常容易地制作出各種類(lèi)型的有用繪圖。

不過(guò),它并沒(méi)有在能力上有所妥協(xié)!Seaborn 提供了訪(fǎng)問(wèn)底層 Matplotlib 對(duì)象的逃生艙口,所以你仍然可以進(jìn)行完全控制。

Seaborn 的代碼比原始的 Matplotlib 更簡(jiǎn)單(可在此處運(yùn)行):

  1. import seaborn as sns 
  2. from votes import long as df 
  3. # Some boilerplate to initialise things 
  4. sns.set() 
  5. plt.figure() 
  6. # This is where the actual plot gets made 
  7. ax = sns.barplot(data=dfx="year"y="seats"hue="party"palette=['blue', 'red', 'yellow', 'grey'], saturation=0.6) 
  8. # Customise some display properties 
  9. ax.set_title('UK election results') 
  10. ax.grid(color='#cccccc'
  11. ax.set_ylabel('Seats') 
  12. ax.set_xlabel(None) 
  13. ax.set_xticklabels(df["year"].unique().astype(str), rotation='vertical'
  14. # Ask Matplotlib to show it 
  15. plt.show() 

并生成這樣的圖表:

Seaborn plot of British election data

Plotly

Plotly 是一個(gè)繪圖生態(tài)系統(tǒng),它包括一個(gè) Python 繪圖庫(kù)。它有三個(gè)不同的接口:

  • 一個(gè)面向?qū)ο蟮慕涌凇?/li>
  • 一個(gè)命令式接口,允許你使用類(lèi)似 JSON 的數(shù)據(jù)結(jié)構(gòu)來(lái)指定你的繪圖。
  • 類(lèi)似于 Seaborn 的高級(jí)接口,稱(chēng)為 Plotly Express。

Plotly 繪圖被設(shè)計(jì)成嵌入到 Web 應(yīng)用程序中。Plotly 的核心其實(shí)是一個(gè) JavaScript 庫(kù)!它使用 D3 和 stack.gl 來(lái)繪制圖表。

你可以通過(guò)向該 JavaScript 庫(kù)傳遞 JSON 來(lái)構(gòu)建其他語(yǔ)言的 Plotly 庫(kù)。官方的 Python 和 R 庫(kù)就是這樣做的。在 Anvil,我們將 Python Plotly API 移植到了 Web 瀏覽器中運(yùn)行。

這是使用 Plotly 的源代碼(你可以在這里運(yùn)行):

  1. import plotly.graph_objects as go 
  2.     from votes import wide as df 
  3.     #  Get a convenient list of x-values 
  4.     years = df['year'] 
  5.     x = list(range(len(years))) 
  6.     # Specify the plots 
  7.     bar_plots = [ 
  8.         go.Bar(xx=x, y=df['conservative'], name='Conservative'marker=go.bar.Marker(color='#0343df')), 
  9.         go.Bar(xx=x, y=df['labour'], name='Labour'marker=go.bar.Marker(color='#e50000')), 
  10.         go.Bar(xx=x, y=df['liberal'], name='Liberal'marker=go.bar.Marker(color='#ffff14')), 
  11.         go.Bar(xx=x, y=df['others'], name='Others'marker=go.bar.Marker(color='#929591')), 
  12.     ] 
  13.     # Customise some display properties 
  14.     layout = go.Layout( 
  15.         title=go.layout.Title(text="Election results"x=0.5), 
  16.         yaxis_title="Seats"
  17.         xaxis_tickmode="array"
  18.         xaxis_tickvals=list(range(27)), 
  19.         xaxis_ticktext=tuple(df['year'].values), 
  20.     ) 
  21.     # Make the multi-bar plot 
  22.     fig = go.Figure(data=bar_plotslayoutlayout=layout) 
  23.     # Tell Plotly to render it 
  24.     fig.show() 

Bokeh

Bokeh(發(fā)音為 “BOE-kay”)擅長(zhǎng)構(gòu)建交互式繪圖,所以這個(gè)標(biāo)準(zhǔn)的例子并沒(méi)有將其展現(xiàn)其最好的一面。和 Plotly 一樣,Bokeh 的繪圖也是為了嵌入到 Web 應(yīng)用中,它以 HTML 文件的形式輸出繪圖。

下面是使用 Bokeh 的代碼(你可以在這里運(yùn)行):

  1. from bokeh.io import show, output_file 
  2.    from bokeh.models import ColumnDataSource, FactorRange, HoverTool 
  3.    from bokeh.plotting import figure 
  4.    from bokeh.transform import factor_cmap 
  5.    from votes import long as df 
  6.    # Specify a file to write the plot to 
  7.    output_file("elections.html") 
  8.    # Tuples of groups (year, party) 
  9.    x = [(str(r[1]['year']), r[1]['party']) for r in df.iterrows()] 
  10.    y = df['seats'] 
  11.    # Bokeh wraps your data in its own objects to support interactivity 
  12.    source = ColumnDataSource(data=dict(xx=x, yy=y)) 
  13.    # Create a colourmap 
  14.    cmap = { 
  15.        'Conservative': '#0343df', 
  16.        'Labour': '#e50000', 
  17.        'Liberal': '#ffff14', 
  18.        'Others': '#929591', 
  19.    } 
  20.    fill_color = factor_cmap('x', palette=list(cmap.values()), factors=list(cmap.keys()), start=1end=2
  21.    # Make the plot 
  22.    p = figure(x_range=FactorRange(*x), width=1200title="Election results"
  23.    p.vbar(x='x'top='y'width=0.9, sourcesource=source, fill_colorfill_color=fill_color, line_color=fill_color
  24.    # Customise some display properties 
  25.    p.y_range.start = 0 
  26.    p.x_range.range_padding = 0.1 
  27.    p.yaxis.axis_label = 'Seats' 
  28.    p.xaxis.major_label_orientation = 1 
  29.    p.xgrid.grid_line_color = None 

圖表如下:

Bokeh plot of British election data

Altair

Altair 是基于一種名為 Vega 的聲明式繪圖語(yǔ)言(或“可視化語(yǔ)法”)。這意味著它具有經(jīng)過(guò)深思熟慮的 API,可以很好地?cái)U(kuò)展復(fù)雜的繪圖,使你不至于在嵌套循環(huán)的地獄中迷失方向。

與 Bokeh 一樣,Altair 將其圖形輸出為 HTML 文件。這是代碼(你可以在這里運(yùn)行):

  1. import altair as alt 
  2.     from votes import long as df 
  3.     # Set up the colourmap 
  4.     cmap = { 
  5.         'Conservative': '#0343df', 
  6.         'Labour': '#e50000', 
  7.         'Liberal': '#ffff14', 
  8.         'Others': '#929591', 
  9.     } 
  10.     # Cast years to strings 
  11.     df['year'] = df['year'].astype(str) 
  12.     # Here's where we make the plot 
  13.     chart = alt.Chart(df).mark_bar().encode( 
  14.         x=alt.X('party', title=None), 
  15.         y='seats'
  16.         column=alt.Column('year', sort=list(df['year']), title=None), 
  17.         color=alt.Color('party', scale=alt.Scale(domain=list(cmap.keys()), range=list(cmap.values()))) 
  18.     ) 
  19.     # Save it as an HTML file. 
  20.     chart.save('altair-elections.html') 

結(jié)果圖表:

Altair plot of British election dataPygal

Pygal

專(zhuān)注于視覺(jué)外觀(guān)。它默認(rèn)生成 SVG 圖,所以你可以無(wú)限放大它們或打印出來(lái),而不會(huì)被像素化。Pygal 繪圖還內(nèi)置了一些很好的交互性功能,如果你想在 Web 應(yīng)用中嵌入繪圖,Pygal 是另一個(gè)被低估了的候選者。

代碼是這樣的(你可以在這里運(yùn)行它):

  1. import pygal 
  2.    from pygal.style import Style 
  3.    from votes import wide as df 
  4.    # Define the style 
  5.    custom_style = Style
  6.        colors=('#0343df', '#e50000', '#ffff14', '#929591') 
  7.        font_family='Roboto,Helvetica,Arial,sans-serif'
  8.        background='transparent'
  9.        label_font_size=14
  10.    ) 
  11.    # Set up the bar plot, ready for data 
  12.    c = pygal.Bar( 
  13.        title="UK Election Results"
  14.        style=custom_style
  15.        y_title='Seats'
  16.        width=1200
  17.        x_label_rotation=270
  18.    ) 
  19.    # Add four data sets to the bar plot 
  20.    c.add('Conservative', df['conservative']) 
  21.    c.add('Labour', df['labour']) 
  22.    c.add('Liberal', df['liberal']) 
  23.    c.add('Others', df['others']) 
  24.    # Define the X-labels 
  25.    c.x_labels = df['year'] 
  26.    # Write this to an SVG file 
  27.    c.render_to_file('pygal.svg') 

繪制結(jié)果:

Pygal plot of British election data

Pandas

Pandas 是 Python 的一個(gè)極其流行的數(shù)據(jù)科學(xué)庫(kù)。它允許你做各種可擴(kuò)展的數(shù)據(jù)處理,但它也有一個(gè)方便的繪圖 API。因?yàn)樗苯釉跀?shù)據(jù)幀上操作,所以 Pandas 的例子是本文中最簡(jiǎn)潔的代碼片段,甚至比 Seaborn 的代碼還要短!

Pandas API 是 Matplotlib 的一個(gè)封裝器,所以你也可以使用底層的 Matplotlib API 來(lái)對(duì)你的繪圖進(jìn)行精細(xì)的控制。

這是 Pandas 中的選舉結(jié)果圖表。代碼精美簡(jiǎn)潔!

  1. from matplotlib.colors import ListedColormap 
  2.  from votes import wide as df 
  3.  cmap = ListedColormap(['#0343df', '#e50000', '#ffff14', '#929591']) 
  4.  ax = df.plot.bar(x='year'colormap=cmap
  5.  ax.set_xlabel(None) 
  6.  ax.set_ylabel('Seats') 
  7.  ax.set_title('UK election results') 
  8.  plt.show() 

繪圖結(jié)果:

Pandas plot of British election data要運(yùn)行這個(gè)例子,請(qǐng)看這里

以你的方式繪制

Python 提供了許多繪制數(shù)據(jù)的方法,無(wú)需太多的代碼。雖然你可以通過(guò)這些方法快速開(kāi)始創(chuàng)建你的繪圖,但它們確實(shí)需要一些本地配置。如果需要,Anvil 為 Python 開(kāi)發(fā)提供了精美的 Web 體驗(yàn)。祝你繪制愉快!

 

 

 

責(zé)任編輯:趙寧寧 來(lái)源: Linux中國(guó)
相關(guān)推薦

2020-06-12 07:57:55

Java框架編程語(yǔ)言Java

2017-11-03 10:40:25

Python復(fù)制文件方法

2019-10-10 10:19:23

智能數(shù)據(jù)大數(shù)據(jù)軟件

2020-05-27 10:49:33

智慧城市物聯(lián)網(wǎng)病毒

2020-01-06 10:01:12

JavaScript瀏覽器HTML

2021-12-01 23:16:44

工具數(shù)據(jù)處理

2019-05-08 12:15:12

Web挖掘工具

2020-05-29 09:56:31

數(shù)據(jù)分析數(shù)據(jù)大數(shù)據(jù)

2021-09-08 13:27:49

人工智能物流行業(yè)AI

2020-04-27 08:44:07

語(yǔ)音欺詐黑客惡意攻擊

2018-03-13 09:34:30

人工智能編程語(yǔ)言Python

2018-09-14 14:27:43

2011-04-27 09:12:14

PHPjavascriptjava

2023-09-06 11:35:11

2020-05-06 07:26:55

容器性能監(jiān)控云計(jì)算

2022-05-08 22:09:28

網(wǎng)絡(luò)拓?fù)?/a>網(wǎng)絡(luò)技術(shù)網(wǎng)絡(luò)

2022-12-09 00:09:10

編程語(yǔ)言開(kāi)發(fā)人員通信

2020-04-26 10:05:29

編程程序員技術(shù)

2013-04-19 09:47:30

虛擬化數(shù)據(jù)

2013-07-19 11:12:28

虛擬化數(shù)據(jù)丟失
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 日韩精品不卡 | 免费网站国产 | 国产成人免费视频网站高清观看视频 | 亚洲激情第一页 | 天天操欧美 | 亚洲一区二区三区在线视频 | 午夜国产在线 | 伊人热久久 | 国产成人99久久亚洲综合精品 | 亚洲午夜精品视频 | 日韩福利在线观看 | 成人av激情 | 国产午夜精品久久久久免费视高清 | 神马久久春色视频 | 成人免费精品视频 | 国产乱码精品一区二区三区五月婷 | 国产精品海角社区在线观看 | www视频在线观看 | 99亚洲 | 日韩在线中文 | v片网站 | 一区二区三区精品视频 | 国产精品一区视频 | 北条麻妃99精品青青久久 | 欧美国产中文字幕 | 日韩在线观看 | 农村真人裸体丰满少妇毛片 | 天堂一区二区三区 | 亚洲网站在线观看 | 99爱免费 | 亚洲一二三视频 | 欧美激情精品久久久久久变态 | 国产亚洲一区精品 | 成人黄色a | 免费在线观看成人 | 国产不卡在线播放 | 国产人成精品一区二区三 | 羞羞视频在线网站观看 | 欧美高清视频在线观看 | 久久精品成人 | 中文字幕成人 |