绘图: Python matplotlib简介
作者:Vamei 出處:http://www.cnblogs.com/vamei 歡迎轉載,也請保留這段聲明。謝謝!
?
matplotlib是基于numpy的一套Python工具包。這個包提供了豐富的數據繪圖工具,主要用于繪制一些統計圖形。你可以找到很多各式各樣的例子:
?
通過數據繪圖,我們可以將枯燥的數字轉換成容易被人們接受的圖表,從而讓人留下更加深刻的印象。實際上,早在一百多年前,南丁格爾就曾經用統計圖形來說服英國政府,以改善軍隊的衛生狀況。
我們將以GDP數據為例子,看看如何繪制經典的餅圖和條形圖。
?
數據
下面是我們要使用的數據,為2011年GDP前十的國家以及其具體的GDP:
USA 15094025 China 11299967 India 4457784 Japan 4440376 Germany 3099080 Russia 2383402 Brazil 2293954 UK 2260803 France 2217900 Italy ? ? ? 1846950?
餅圖
我們先來繪制餅圖 (pie plot)。餅圖適用于表達各個國家GDP所占的百分比。每一小塊的面積代表了占比的多少:
具體代碼如下,可以看到我們主要使用了matplotlib.pyplot工具包:
# Make a pie chart # This script is written by Vamei, http://www.cnblogs.com/vamei # you may freely use it.import matplotlib.pyplot as plt # quants: GDP # labels: country name labels = [] quants = [] # Read data for line in file('../data/major_country_gdp'):info = line.split()labels.append(info[0])quants.append(float(info[1]))# make a square figure plt.figure(1, figsize=(6,6))# For China, make the piece explode a bit def explode(label, target='China'):if label == target: return 0.1else: return 0 expl = map(explode,labels) # Colors used. Recycle if not enough. colors = ["pink","coral","yellow","orange"] # Pie Plot # autopct: format of "percent" string; plt.pie(quants, explode=expl, colors=colors, labels=labels, autopct='%1.1f%%',pctdistance=0.8, shadow=True) plt.title('Top 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5})plt.show()?
條形圖
下面我們嘗試一下條形圖(bar plot)。用每個長條的高度代表每個國家的GDP,長條越高,GDP值越高:
代碼如下:
""" Make a pie chart This script is written by Vamei, http://www.cnblogs.com/vamei you may freely use it. """ import matplotlib.pyplot as plt import numpy as np # quants: GDP # labels: country name labels = [] quants = [] # Read data for line in file('../data/major_country_gdp'):info = line.split()labels.append(info[0])quants.append(float(info[1]))width = 0.4 ind = np.linspace(0.5,9.5,10) # make a square figure fig = plt.figure(1, figsize=(12,6)) ax = fig.add_subplot(111) # Bar Plot ax.bar(ind-width/2,quants,width,color='coral')# Set the ticks on x-axis ax.set_xticks(ind) ax.set_xticklabels(labels) # labels ax.set_xlabel('Country') ax.set_ylabel('GDP (Billion US dollar)') # title ax.set_title('Top 10 GDP Countries', bbox={'facecolor':'0.8', 'pad':5}) plt.show()該代碼中我們利用了ax對象,以便控制刻度以及刻度所對應的國家名。這與我們在pie plot所做的有些不同(pie plot也可以這樣實現,只是沒有必要而已)。
?
從兩個圖上看,亞洲國家的GDP還是很厲害的。西方的話就是美國一枝獨秀了。
?
總結
我們演示了餅圖和條性圖的繪制方法。matplotlib是一款功能強大的數據繪圖工具,非常值得學習。
轉載于:https://www.cnblogs.com/vamei/archive/2012/09/17/2689798.html
總結
以上是生活随笔為你收集整理的绘图: Python matplotlib简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: IOS学习之UINavigationCo
- 下一篇: ubuntu源