![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAjM2EzLcd3LcJzLcJzdllmVldWYtl2PnVGcq5iN1AHc3oXdxYXcvw1M1EDOwYTMtUGall3LcVmdhNXLwRHdo9CXt92YucWbpRWdvx2Yx5yazF2Lc9CX6MHc0RHaiojIsJye.jpeg)
總第57篇
01|Figure和Subplot:
matplotlib的圖像都位于figure對象中,相當于一塊畫布。figure的屬性figsize是用來設定figure的大小的。subplot是用來存放坐标系的,一個figure中可以有多個subplot。
%matplotlib inline
import matplotlib.pyplot as plt
from numpy.random import randn
import numpy as np
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)#表示在figure中建立2*2個坐标系,ax1位于第一個坐标中
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
在程式開頭加(%matplotlib)是為了顯示figure,如果不加則不會跳出figure圖框。而(%matplotlib inline)則是直接顯示在程式設計界面,不重新跳出做圖框。
如果我們沒有指定在哪個ax上進行作圖,matplotlib會預設選擇最後一個(如果沒有則建立一個)上進行繪制。下面這條指令就沒有指定。
plt.plot(randn(50).cumsum(),"k--")
ax1.hist(randn(100),bins=20,color='k',alpha=0.3)#在ax1上作圖
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))#在ax2上作圖
也可以直接一次性建立多個圖框,然後在使用的時候進行索引使用就行,比如下面的subplots(2,3)就是一次性建立兩行三列個坐标,而axes[0,1]則表示利用第0行第2列對應的圖框。
fig,axes=plt.subplots(2,3)
_=axes[0,1].hist(randn(100),bins=20,color='k',alpha=0.3)#加“_=”視為讓其不輸出randn産生的随機數組
subplots的參數:除幾行幾列外,還有sharex和sharey,表示x(y)軸的刻度是否要保持相等的刻度。預設情況是False,即不相等。
調整subplot周圍的間距:預設情況下,matlibplot會在subplot外圍以及sbuplot之間留下一定的邊距。圖像的大小和間距是相關的,如果你調整了圖像大小,間距也會自動調整。利用Figure的subplots_adjust方法可以用來修改間距。
plt.subplots_adjust(left=None,right=None,top=None,bottom=None,wspace=None,hspace=None)#分别表示左右上下邊距,以及寬度和高度百分比。
02|顔色,标記和線型:
常用顔色用英文字母的首字母來代替。
b---blue c---cyan g---green k----black
m---magenta r---red w---white y----yellow
标記是用線上性圖上來強調實際資料點的。
. Point marker
, Pixel marker
o Circle marker
v Triangle down marker
^ Triangle up marker
< Triangle left marker
> Triangle right marker
1 Tripod down marker
2 Tripod up marker
3 Tripod left marker
4 Tripod right marker
s Square marker
p Pentagon marker
* Star marker
h Hexagon marker
H Rotated hexagon D Diamond marker
d Thin diamond marker
| Vertical line (vlinesymbol) marker
_ Horizontal line (hline symbol) marker
+ Plus marker
x Cross (x) marker
線性是表示線的形狀。
- 實線
-- 短線
-. 短點相間線
: 虛點線
plot(randn(30).cumsum(),color="k",linestyle="--",marker="o")
03|刻度、标簽和标題:
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum())
ticks=ax.set_xticks([0,250,500,750,1000])#設定x軸的刻度,y軸把x換成y即可
lables=ax.set_xticklabels(["one","two","three","four","five"],rotation=30,fontsize="small")#設定x軸對應的标簽,y軸把x換成y即可
ax.set_title("my first matplotlib plot")#為坐标軸設定标題
04|圖例:
在添加subplot的時候傳入label參數,然後調用ax.legend()或plt.legend()即可。
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum(),label="one")#建立label标簽
ax.plot(randn(1000).cumsum(),label="two")#建立label标簽
ax.plot(randn(1000).cumsum(),label="three")#建立label标簽
ax.legend(loc="best")#loc是用來說明圖例的放置位置
06|Pandas作圖:
matplotlib是一種比較低級的工具,要組裝一張圖表,需要用到它的各種元件才可以,包括圖表類型(線型圖、柱狀圖、盒形圖、散布圖、等值線圖等)、圖例、标題、刻度标簽以及其他注釋資訊。這是因為制作一張完整的圖表都需要用到這些,但是matplotlib要實作這種功能需要很多行代碼,而pandas可能隻需要幾行代碼就可以搞定。
- 線型圖:Series和DataFrame都有自己的plot方法,plot預設建立的是線形圖,Series.plot()和DataFrame.plot()。
- 柱狀圖:需要給plot方法傳入參數kind,其中kind="bar"表垂直柱狀圖、kind="barh"表水準柱狀圖。Series和DataFrame的索引将會被用作X(或Y)軸的刻度。柱狀圖中有個特例就是堆積柱狀圖,隻需要給plot傳入參數stacked="True"即可。還可以利用s.value_counts().plot(kind="bar")來圖形化顯示Series中各值出現的頻率。
- 直方圖:是一種可以對值頻率離散化顯示的柱狀圖。通過調用Series.hist()方法即可建立。
- 密度圖:與直方圖相關的一種類型圖,是通過計算“可能會産生觀測資料的連續機率分布的估計”而産生的,通過給plot傳入參數kind="kde"即可。
- 散布圖:是觀測兩個一維資料序列之間關系的有效手段,使用pd.scatter_matrix()即可建立。