原文地址: !()[http://www.bugingcode.com/blog/Matplotlib_7_Effectively_Using.html]html
這是一篇關於如何高效的使用Matplotlib
的文章,文章的地址在 原文,可是這裏不許備一行一行的對文章的內容進行翻譯,而是把主要的步驟和思想都記錄下來,在進行項目繪製的時候可以有很好的幫助。python
獲取數據和數據格式
要進行數據的繪製時,數據通常存放在文檔裏,好比cvs或者是excel中,讀取時使用 pandas
進行操做,這裏 下有專門的介紹,這裏不在詳細的介紹了。git
數據從 https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true 中獲得,這裏看看數據的讀取和格式:github
import matplotlib.pyplot as plt import numpy as np from scipy import stats import pandas as pd from matplotlib.ticker import FuncFormatter df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true") print df.head()
這裏打印出sample-salesv3.xlsx 中前面4行的數據,數據的格式以下所示:編程
商品id,商品名稱,商品sku,銷售數量,銷售單價,產品銷售額,時間。canvas
數據排行和展現
咱們想知道哪些商品的銷售最高,須要對數據進行排序,並取到前10位:ide
import matplotlib.pyplot as plt import numpy as np from scipy import stats import pandas as pd from matplotlib.ticker import FuncFormatter df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true") #對ext price 進行排序,並取得前10位 top_10 = (df.groupby('name')['ext price', 'quantity'].agg({'ext price': 'sum', 'quantity': 'count'}) .sort_values(by='ext price', ascending=False))[:10].reset_index() #從新命名 ext price 換成 Sales,quantity 換成 Purchases top_10.rename(columns={'name': 'Name', 'ext price': 'Sales', 'quantity': 'Purchases'}, inplace=True) print top_10
結果以下:svg
Name Sales Purchases 0 Kulas Inc 137351.96 94 1 White-Trantow 135841.99 86 2 Trantow-Barrows 123381.38 94 3 Jerde-Hilpert 112591.43 89 4 Fritsch, Russel and Anderson 112214.71 81 5 Barton LLC 109438.50 82 6 Will LLC 104437.60 74 7 Koepp Ltd 103660.54 82 8 Frami, Hills and Schmidt 103569.59 72 9 Keeling LLC 100934.30 74
取出了前面10名的銷售額,第一位爲 Kulas Inc,第二位White-Trantow ,等。函數
在圖表上對這些數據進行繪製:url
import matplotlib.pyplot as plt import numpy as np from scipy import stats import pandas as pd from matplotlib.ticker import FuncFormatter df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true") #對ext price 進行排序,並取得前10位 top_10 = (df.groupby('name')['ext price', 'quantity'].agg({'ext price': 'sum', 'quantity': 'count'}) .sort_values(by='ext price', ascending=False))[:10].reset_index() #從新命名 ext price 換成 Sales,quantity 換成 Purchases top_10.rename(columns={'name': 'Name', 'ext price': 'Sales', 'quantity': 'Purchases'}, inplace=True) plt.style.use('ggplot') top_10.plot(kind='barh', y="Sales", x="Name") plt.show()
獲得各個商品的銷售額:
圖表自定義
自定義在圖表的繪製中起到了美化和加強可讀性的做用,對圖表的說明和樣式的改變,可以使你的圖表看上去專業不少。
對圖表的說明和座標範圍限制:
把上面 top_10.plot(kind='barh', y="Sales", x="Name")
代碼更換爲如下的代碼,代碼的功能也很清楚,限制x軸座標,設置標題,x軸說明:
fig, ax = plt.subplots(figsize=(5, 6)) top_10.plot(kind='barh', y="Sales", x="Name", ax=ax) ax.set_xlim([-10000, 140000]) ax.set(title='2014 Revenue', xlabel='Total Revenue') ax.legend().set_visible(False)
獲得的結果圖以下:
要想修改這個圖像,你可能須要執行不少操做。圖中最礙眼的多是總收益額的格式。Matplotlib 能夠使用 FuncFormatter 解決這一問題。該函數用途多樣,容許用戶定義的函數應用到值,並返回格式美觀的字符串。
如下是貨幣格式化函數,用於處理數十萬美圓區間的數值:
def currency(x, pos): 'The two args are the value and tick position' if x >= 1000000: return '${:1.1f}M'.format(x*1e-6) return '${:1.0f}K'.format(x*1e-3)
對x軸數據格式進行說明:
formatter = FuncFormatter(currency) ax.xaxis.set_major_formatter(formatter)
一樣的總的代碼是把plot的代碼替換爲以下:
fig, ax = plt.subplots() top_10.plot(kind='barh', y="Sales", x="Name", ax=ax) ax.set_xlim([-10000, 140000]) ax.set(title='2014 Revenue', xlabel='Total Revenue', ylabel='Customer') formatter = FuncFormatter(currency) ax.xaxis.set_major_formatter(formatter) ax.legend().set_visible(False)
對x軸進行修飾之後的圖表:
多圖表對比
各個銷售的對比和各個商品在總體中是處於哪一個地位是較爲關心的話題。把平均值也繪製在圖表中,能夠很方便的進行對比。
# Create the figure and the axes fig, ax = plt.subplots() # Plot the data and get the averaged top_10.plot(kind='barh', y="Sales", x="Name", ax=ax) avg = top_10['Sales'].mean() # Set limits and labels ax.set_xlim([-10000, 140000]) ax.set(title='2014 Revenue', xlabel='Total Revenue', ylabel='Customer') # Add a line for the average ax.axvline(x=avg, color='b', label='Average', linestyle='--', linewidth=1) # Format the currency formatter = FuncFormatter(currency) ax.xaxis.set_major_formatter(formatter) # Hide the legend ax.legend().set_visible(False)
圖表以下:
目前,咱們所作的全部改變都是針對單個圖表。咱們還可以在圖像上添加多個表,使用不一樣的選項保存整個圖像。
在這個例子中,我使用 nrows 和 ncols 指定大小,這對新用戶來講比較清晰易懂。我還使用 sharey=True 以使 y 軸共享相同的標籤。
該示例很靈活,由於不一樣的軸能夠解壓成 ax0 和 ax1。如今咱們有了這些軸,就能夠像上述示例中那樣繪圖,而後把一個圖放在 ax0 上,另外一個圖放在 ax1。
# Get the figure and the axes fig, (ax0, ax1) = plt.subplots(nrows=1,ncols=2, sharey=True, figsize=(7, 4)) top_10.plot(kind='barh', y="Sales", x="Name", ax=ax0) ax0.set_xlim([-10000, 140000]) ax0.set(title='Revenue', xlabel='Total Revenue', ylabel='Customers') # Plot the average as a vertical line avg = top_10['Sales'].mean() ax0.axvline(x=avg, color='b', label='Average', linestyle='--', linewidth=1) # Repeat for the unit plot top_10.plot(kind='barh', y="Purchases", x="Name", ax=ax1) avg = top_10['Purchases'].mean() ax1.set(title='Units', xlabel='Total Units', ylabel='') ax1.axvline(x=avg, color='b', label='Average', linestyle='--', linewidth=1) # Title the figure fig.suptitle('2014 Sales Analysis', fontsize=14, fontweight='bold'); # Hide the legends ax1.legend().set_visible(False) ax0.legend().set_visible(False)
保存圖表
Matplotlib 支持多種不一樣文件保存格式。你能夠使用 fig.canvas.get_supported_filetypes() 查看系統支持的文件格式:
fig.canvas.get_supported_filetypes() {'eps': 'Encapsulated Postscript', 'jpeg': 'Joint Photographic Experts Group', 'jpg': 'Joint Photographic Experts Group', 'pdf': 'Portable Document Format', 'pgf': 'PGF code for LaTeX', 'png': 'Portable Network Graphics', 'ps': 'Postscript', 'raw': 'Raw RGBA bitmap', 'rgba': 'Raw RGBA bitmap', 'svg': 'Scalable Vector Graphics', 'svgz': 'Scalable Vector Graphics', 'tif': 'Tagged Image File Format', 'tiff': 'Tagged Image File Format'}
咱們有 fig 對象,所以咱們能夠將圖像保存成多種格式:
fig.savefig('sales.png', transparent=False, dpi=80, bbox_inches="tight")
轉載請標明來之:http://www.bugingcode.com/
更多教程:阿貓學編程