原文地址: !()[http://www.bugingcode.com/blog/Matplotlib_7_Effectively_Using.html]
這是一篇關於如何高效的使用Matplotlib
的文章,文章的地址在 原文,但是這里不准備一行一行的對文章的內容進行翻譯,而是把主要的步驟和思想都記錄下來,在進行項目繪制的時候能夠有很好的幫助。
獲取數據和數據格式
要進行數據的繪制時,數據一般存放在文檔里,比如cvs或者是excel中,讀取時使用 pandas
進行操作,這里 下有專門的介紹,這里不在詳細的介紹了。
數據從 https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true 中得到,這里看看數據的讀取和格式:
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,銷售數量,銷售單價,產品銷售額,時間。
數據排行和展示
我們想知道哪些商品的銷售最高,需要對數據進行排序,並取到前10位:
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
結果如下:
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 ,等。
在圖表上對這些數據進行繪制:
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/
更多教程:阿貓學編程