matplotlib是python中的一個數據可視化庫,可以做出很多數據統計圖,下面來說一說matplotlib的一些基本使用。
1.首先引入和數據分析有關的庫。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
2.然後使用pandas讀入數據。
3.fig = plt.figure(figsize=(m,n))
:規定一個長爲m,寬爲n的畫圖區域。
4.plt.xlabel("")
:規定橫軸名稱。
5.plt.ylabel("")
:規定縱軸名稱。
6.plt.title("")
:規定圖像名稱。
7.plt.xticks(rotation=k)
:將x軸的各標籤旋轉k度。
8.plt.legend(loc="best)
:添加圖例,loc爲圖例的位置,傳入best系統會自動尋找最佳的圖例位置。下圖爲繪製五條折線。
fig = plt.figure(figsize=(10,7)) #規定繪圖區域大小
color = ["green","cyan","yellow","red","black"] #指定五條折線的顏色
plt.xlabel("Month")
plt.ylabel("Unemployment Rate")
plt.title("Unemployment Statics Trend,1948")
for i in range(5):
x = i*12
y = (i+1)*12
subset = unrate[x:y]
label = str(1948+i)
plt.plot(subset["MONTH"],subset["VALUE"],c=color[i],label=label)
plt.legend(loc="best") #添加圖例到最佳顯示位置
plt.show()
9.fig.add_subplot()
:添加子圖繪製區域。
fig = plt.figure(figsize=(10,8))
ax1 = fig.add_subplot(2,2,1) #指定子圖位置
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
plt.show()
10.ax.set_xticks()
:指定x軸繪圖座標。
11.ax.set_xticklabels()
:指定x軸每個標籤的名字。
12.ax.set_xlabel()
、ax.set_ylabel()
、ax.set_title()
:分別指定x軸,y軸,圖像名稱。
num_cols = ['RT_user_norm', 'Metacritic_user_nom', 'IMDB_norm', 'Fandango_Ratingvalue', 'Fandango_Stars']
bar_heights = norm_reviews.loc[0,num_cols].values
print(bar_heights)
bar_positions = np.arange(5)
print(bar_positions)
tick_positions = range(0,5)
fig,ax = plt.subplots(figsize=(10,8)) #用ax畫圖,fig控制區域
plt.bar(bar_positions,bar_heights,0.6) #0.6表示所畫條形圖每個圖形的寬度
ax.set_xticks(tick_positions)
ax.set_xticklabels(num_cols,rotation=45)
ax.set_xlabel("Rating Source")
ax.set_ylabel("Average Rating")
ax.set_title("Average User Rating For Avengers:Age of Ultron(2015)")
plt.show()
13.如果要讓條形圖橫着畫,只需將繪製條形圖的命令plt.bar()
改爲plt.barh()
,如果有需要再重新指定一下自己所需的橫縱座標即可。
14.plt.scatter()
:繪製散點圖。
15.plt.hist(x,bins=k,range=(m,n))
:繪製直方圖,bins指定繪製出數據的條數,range()指定直方圖橫座標的取值範圍。
16.ax.boxplot()
:繪製盒形圖,盒形圖可以直觀的觀察出數據的離羣點,也就是不符合規範的數據,具體到seaborn庫時會講。