Matplotlib
我們學習完Python中用於數據處理的Numpy和Pandas之后, 我們需要再學習一些關於數據可視化的庫--matplotlib.
在數據分析工作中, 人們往往對數據可視化這一步不夠重視, 實際上它非常重要, 因為錯誤或不充分的數據表示方法可能會毀掉原本出色的數據分析工作.我們下面將會學習matplotlib庫各方面的知識
4.1 概述
matplotlib庫不是一個單獨的應用,而是Python語言的一個庫. 專門用於開發2D圖表. 它具有以下優點:
matplotlib庫不是一個單獨的應用,而是Python語言的一個庫. 專門用於開發2D圖表. 它具有以下優點:
- 使用起來極其簡單.
- 以漸進、交互式方式實現數據可視化.
- 對圖像元素控制能力更強.
- 可輸出PNG、PDF等多種格式.
Ubuntu和Mac上直接通過命令安裝:
pip install matplotlib
線性圖和案例
from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt x = np.arange(1, 11) y = np.random.randint(1, 10, 10) # 調用繪制線性圖函數plot() plt.plot(x, y) # 調用show方法顯式 plt.show()
線條和標記節點樣式: 標記字符:標記線條中的點
- 線條顏色,color='g'
- 線條風格,linestyle='--'
- 線條粗細,linewidth=5.0
- 標記風格,marker='o'
- 標記顏色,markerfacecolor='b'
- 標記尺寸,markersize=20
- 透明度,alpha=0.5
- 線條和標記節點格式字符 如果不設置顏色,系統默認會取一個不同顏色來區別線條.
顏色字符(color) | 風格(linestyle) | 標記字符(mark) |
---|---|---|
r 紅色 | - 實線 | o實心圈標記 |
g 綠色 | -- 虛線,破折線 | . 點標記 |
b 藍色 | -. 點划線 | , 像素標記,極小的點 |
w 白色 | : 點虛線,虛線 | v 倒三角標記 |
c 青色 | '' 留空或空格,無線條 | ^ 上三角標記 |
m 洋紅 | > 右三角標記 | |
y 黃色 | < 左三角標記 | |
k 黑色 | * 星形標記 | |
#00ff00 16進制 | + 十字標記 |
設置 x, y 值從什么時候開始到什么值結束,自定義x和y顯示的值
from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt plt.plot(np.arange(5), np.arange(5,10), marker='o', markersize=6, markerfacecolor='r', # linestyle='-.', # linewidth=5, # alpha=0.8 ) # 設置 x, y 值從什么時候開始到什么值結束 plt.xlim(0, 5) plt.ylim(0, 9) plt.xticks([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], rotation=-40) plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], list('abcdefghij')) plt.show()
通過 plt.text 函數增加文本信息(根據坐標來設置文本位置)
from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt x = np.arange(5) y = np.arange(5,10) plt.plot(x, y, marker='o', markersize=6, markerfacecolor='r', # linestyle='-.', # linewidth=5, # alpha=0.8 ) # 設置 x, y 值從什么時候開始到什么值結束 plt.xlim(0, 5) plt.ylim(0, 9) plt.xticks([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], rotation=-40) plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], list('abcdefghij')) for a, b in zip(x, y): plt.text(a-0.1, b+0.3, str(b)) plt.show()
增加網格 通過設置 plt.grid(True)
from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt x = np.arange(5) y = np.arange(5,10) plt.plot(x, y, marker='o', markersize=6, markerfacecolor='r', # linestyle='-.', # linewidth=5, # alpha=0.8 ) # 設置 x, y 值從什么時候開始到什么值結束 plt.xlim(0, 5) plt.ylim(0, 9) plt.xticks([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], rotation=-40) plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], list('abcdefghij')) for a, b in zip(x, y): plt.text(a-0.1, b+0.3, str(b)) # 增加網格 plt.grid(True) plt.show()
設置圖形顯示的尺寸 plt.figure(figsize=(12, 6))

from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt x = np.arange(5) y = np.arange(5,10) plt.figure(figsize=(12, 6)) plt.plot(x, y, marker='o', markersize=6, markerfacecolor='r', # linestyle='-.', # linewidth=5, # alpha=0.8 ) # 設置 x, y 值從什么時候開始到什么值結束 plt.xlim(0, 5) plt.ylim(0, 9) plt.xticks([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], rotation=-40) plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], list('abcdefghij')) for a, b in zip(x, y): plt.text(a-0.1, b+0.3, str(b)) # 增加網格 plt.grid(True) plt.show()
增加圖例 plt.legend

from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt x = np.arange(5) y = np.arange(5) # 設置圖片大小 plt.figure(figsize=(12, 6)) line1, = plt.plot(x, y, marker='o', markersize=6, markerfacecolor='r', # linestyle='-.', # linewidth=5, # alpha=0.8 ) line2, = plt.plot([2, 3, 4, 5, 6], [5, 6, 7, 8, 9], marker='o') line3, = plt.plot([4, 5, 6, 7], [5, 6, 7, 8], marker='o') plt.xlim(0, 5) plt.ylim(0, 9) plt.xticks([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], rotation=-40) plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], list('abcdefghij')) # 增加圖例 plt.legend([line1, line2, line3], ['中國', '美國', '小日本'], loc=2, ncol=3) # 增加網格 plt.grid(True) plt.show()
顯示標題和引入字體,顯示 lable

from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties x = np.arange(5) y = np.arange(5) # 設置圖片大小 plt.figure(figsize=(12, 6)) line1, = plt.plot(x, y, marker='o', markersize=6, markerfacecolor='r', # linestyle='-.', # linewidth=5, # alpha=0.8 ) line2, = plt.plot([2, 3, 4, 5, 6], [5, 6, 7, 8, 9], marker='o') line3, = plt.plot([4, 5, 6, 7], [5, 6, 7, 8], marker='o') # 加載字體 font = FontProperties(fname='C:\\Windows\\Fonts\\STSONG.TTF', size=18) font2 = FontProperties(fname='C:\\Windows\\Fonts\\STSONG.TTF', size=12) plt.xlim(0, 5) plt.ylim(0, 9) # rotation 斜體顯示 plt.xticks([0, 1, 2, 3, 4], ['a', 'b', 'c', 'd', 'e'], rotation=-40) plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], list('abcdefghij')) # 增加圖例 plt.legend([line1, line2, line3], ['中國', '美國', '小日本'], loc=2, ncol=3, prop=font2) # 顯示標題 plt.title('中美日三國未來經濟走向', fontproperties=font) plt.xlabel('年限', fontproperties=font) plt.ylabel('國民收入', fontproperties=font) # 增加網格 plt.grid(True) plt.show()
將DataFrame繪制線形圖

from pandas import DataFrame,Series import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties # 加載字體 font = FontProperties(fname='C:\\Windows\\Fonts\\STSONG.TTF', size=18) data_frame1 = pd.DataFrame({ '中國': {2015: 10, 2016: 20, 2017: 30, 2018: 40}, '法國': {2015: 20, 2016: 30, 2017: 40, 2018: 50}, '德國': {2015: 40, 2016: 50, 2017: 60, 2018: 70}, }) plt.plot(data_frame1, marker='o') # 設置圖例 plt.legend(data_frame1, prop=font) plt.grid(True) plt.xticks([x for x in range(2015, 2019)], [x for x in range(2015, 2019)]) plt.show() # 增加網格 plt.grid(True) plt.show()
線形圖案例
數據來源: http://data.stats.gov.cn/easyquery.htm?cn=G0104 數據共20行51列. 歐洲51國家從1997年-2015年旅游收入數據.
完成任務:
- 輸出德國、盧森堡、法國20年旅游收入線性圖.
- 計算歐洲20年旅游收入總和,並繪制線性圖.
import numpy as np import matplotlib.pyplot as plt import pandas as pd from pandas import Series, DataFrame from matplotlib.font_manager import FontProperties # 加載數據 data = pd.read_csv('歐洲國家20年旅游收入數據-utf8.csv', skiprows=3, skipfooter=2, engine='python') # 刪除數據為NaN的列 data.dropna(axis=1, how='all', inplace=True) # 替換NaN值 data.fillna(0, inplace=True) data
data.index = [x for x in range(1996, 2016)][::-1] data
# 設置圖大小 plt.figure(figsize=(16, 9)) # 繪制線性圖 plt.plot(data, marker='o') # 增加網格 plt.grid(True) # 增加標題 # 加載字體 font = FontProperties(fname='/Library/Fonts/Songti.ttc', size=18) font2 = FontProperties(fname='/Library/Fonts/Songti.ttc', size=12) plt.title('法國、德國、盧森堡20年旅游收入線性圖', fontproperties=font) plt.xlim(1996, 2016) plt.ylim(0, 8*10**10) plt.xticks([x for x in range(1996, 2016)], [x for x in range(1996, 2016)]) plt.yticks([x*10**10 for x in range(9)], [str(x)+'百億' for x in range(9)], fontproperties=font2) # 增加圖例 plt.legend(data, prop=font2, loc=2) # 顯示數字 for a,b in zip(data.index, data.values): plt.text(a-0.4, b[0]+2*10**9, '%1.1fY' % (b[0]/(10**9))) plt.text(a-0.4, b[1]+2*10**9, '%1.1fY' % (b[1]/(10**9))) plt.text(a-0.4, b[2]-2*10**9, '%1.1fY' % (b[2]/(10**9))) plt.show()