matplotlib介紹
基本圖形展現(xiàn)
使用plot函數(shù)称龙,首先收藏鏈接:http://matplotlib.org/contents.html
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1,3,2,4]读串,[1,3,2,7],'ro')
plt.ylabel('some numbers')
plt.axis([0, 6, 0, 20])
plt.show()
上面例子里的plot里的list規(guī)定了x和y掂墓,如果缺省一個則將視為y值,后面的‘ro’表示紅色的圈圈演痒,可以做修改能真;
axis()命令給定了坐標范圍,格式是[xmin, xmax, ymin, ymax]胜嗓;
實際上,matplotlib不僅可以用于畫向量钩乍,還可以用于畫多維數(shù)據數(shù)組辞州。
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
格式設置
線形設置
有很多線的性質可供你設置:線寬,虛線格式寥粹,反鋸齒補償变过,等埃元。進一步深入了解參數(shù)可以參見matplotlib.lines.Line2D
·我們可以通過'linewidth'來設置線寬,通過設定set_antialiased來確定是否消除鋸齒
line = plt.plot([1,2,3,4], [1,4,9,16], '-', linewidth=2.0)
line.set_antialiased(False) # 關閉反鋸齒
面我們都只畫了一條線媚狰。這里岛杀,我們采用lines = plot(x1,y1,x2,y2)來畫兩條線≌腹拢可以使用setp()命令楞件,可以像MATLAB一樣設置幾條線的性質。 setp可以使用python 關鍵詞裳瘪,也可用MATLAB格式的字符串。(plt.setp(lines))
lines = plt.plot([1,2,3,4], [1,4,9,16], [1,2,3,4], [16,5,6,2])
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)
我們在作圖中經常用到的性質都在以下列表中給出了:
線型包括
線型 描述
'-' 實線
'--' 虛線
'-.' 點劃線
':' 點
'None', '', 不畫
線標記包括
標記 描述
'o' 圓圈
'D' 鉆石
'h' 六邊形1
'H' 六邊形2
'x' X
'', 'None' 不畫
'8' 八邊形
'p' 五角星
',' 像素點
'+' 加號
'.' 點
's' 正方形
'*' 星型
'd' 窄鉆石
'v' 下三角
'<' 左三角
'>' 右三角
'^' 上三角
顏色 所有的顏色設置可以通過命令matplotlib.pyplot.colors()來查詢
標記 顏色
'b' 藍色
'g' 綠色
'r' 紅色
'c' 藍綠色
'm' 品紅
'y' 黃色
'k' 黑色
'w' 白色
如果上面的顏色還是不夠用罪针,可以采用RGB3元組來定義彭羹,范圍是0~1
比如:color = (0.3, 0.3, 0.4)
color可以被用在一系列和函數(shù)中,這里我們再title中改變color
修改坐標范圍
默認情況下泪酱,坐標軸的最小值和最大值與輸入數(shù)據的最小派殷、最大值一致。也就是說墓阀,默認情況下整個圖形都能顯示在所畫圖片上毡惜,我們可以通過xlim(xmin, xmax)和ylim(ymin, ymax)來調整x,y坐標范圍,見下:
xlim(-2.5, 2.5)
#設置y軸范圍
ylim(-1, 1)
plt.plot(x, y1)
創(chuàng)建子圖
你可以通過plt.figure創(chuàng)建一張新的圖斯撮,plt.subplot來創(chuàng)建子圖经伙。subplot()指令包含numrows(行數(shù)), numcols(列數(shù)), fignum(圖像編號),其中圖像編號的范圍是從1到行數(shù) * 列數(shù)勿锅。在行數(shù) * 列數(shù)<10時帕膜,數(shù)字間的逗號可以省略。
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure(1)
plt.subplot(211)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(212)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
你可以多次使用figure命令來產生多個圖溢十,其中垮刹,圖片號按順序增加。這里张弛,要注意一個概念當前圖和當前坐標荒典。所有繪圖操作僅對當前圖和當前坐標有效。通常吞鸭,你并不需要考慮這些事寺董,下面的這個例子為大家演示這一細節(jié)。
plt.figure(1) # 第一張圖
plt.subplot(211) # 第一張圖中的第一張子圖
plt.plot([1,2,3])
plt.subplot(212) # 第一張圖中的第二張子圖
plt.plot([4,5,6])
plt.figure(2) # 第二張圖
plt.plot([4,5,6]) # 默認創(chuàng)建子圖subplot(111)
plt.figure(1) # 切換到figure 1 ; 子圖subplot(212)仍舊是當前圖
plt.subplot(211) # 令子圖subplot(211)成為figure1的當前圖
plt.title('Easy as 1,2,3') # 添加subplot 211 的標題
添加文字
text()可以在圖中的任意位置添加文字刻剥,并支持LaTex語法
xlable(), ylable()用于添加x軸和y軸標簽
title()用于添加圖的題目
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# 數(shù)據的直方圖
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75)
plt.xlabel('Smarts')
plt.ylabel('Probability')
#添加標題
plt.title('Histogram of IQ')
#添加文字
plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
t0 = plt.text(0.35,0.5,'my text')
plt.setp(t0, color='b',fontsize=24)
t = plt.xlabel('my data', fontsize=14, color='red')
注釋文本
在數(shù)據可視化的過程中螃征,圖片中的文字經常被用來注釋圖中的一些特征。使用annotate()方法可以很方便地添加此類注釋透敌。在使用annotate時盯滚,要考慮兩個點的坐標:被注釋的地方xy(x, y)和插入文本的地方xytext(x, y)
ax = plt.subplot(111)
t = np.arange(0.0, 5.0, 0.01)
s = np.cos(2*np.pi*t)
line, = plt.plot(t, s, lw=2)
plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5),
arrowprops=dict(facecolor='black', shrink=0.05),
)
plt.ylim(-2,2)
plt.show()
圖例
一個圖例包含多個圖例項踢械,每個圖例項由圖例說明和圖例標簽構成
圖例標簽
由彩色的圖案構成,位于圖例說明的左側
圖例說明
圖例標簽的說明文字
使用legend()函數(shù)可以自動添加圖例
line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')
plt.legend(handles=[line_up, line_down])
有時候多個圖例圖例分別添加在不同位置使圖有更強的可讀性魄藕∧诹校可以通過多次調用legned()函數(shù)來實現(xiàn)。添加圖例的位置可以用關鍵詞loc來指定背率。
line1, = plt.plot([1,2,3], label="Line 1", linestyle='--')
line2, = plt.plot([3,2,1], label="Line 2", linewidth=4)
# Create a legend for the first line.
first_legend = plt.legend(handles=[line1], loc=1)
# Add the legend manually to the current Axes.
ax = plt.gca().add_artist(first_legend)
# Create another legend for the second line.
plt.legend(handles=[line2], loc=4)
plt.show()
seaborn介紹
參考以下鏈接:http://seaborn.pydata.org/tutorial.html
格式設置 Style management
seaborn有五種模版darkgrid, whitegrid, dark, white, and ticks可以選擇
sns.set_style("whitegrid")
data = np.random.normal(size=(20, 6)) + np.arange(6) / 2
sns.boxplot(data=data);
可以用下面的命令去掉axes spines
sns.despine()
you can pass a dictionary of parameters to the rc argument of axes_style() and set_style()
sns.set_style("darkgrid", {"axes.facecolor": ".9"})
sinplot()
顏色設置
這里喜歡用的顏色:
漸變藍色:
sns.palplot(sns.color_palette("Blues"))
漸變綠色:
sns.palplot(sns.color_palette("BuGn_r"))
漸變紫色:
sns.palplot(sns.cubehelix_palette(8))
顏色設置方法:
x, y = np.random.multivariate_normal([0, 0], [[1, -.5], [-.5, 1]], size=300).T
cmap = sns.cubehelix_palette(light=1, as_cmap=True)
sns.kdeplot(x, y, cmap=cmap, shade=True);
設置圖像的大小和位置
f, ax = plt.subplots(figsize=(7, 3))
sns.countplot(y="deck", data=titanic, color="c");
各類圖像
分布圖
單變量分布圖
在畫分布圖的時候可以選擇是否加陰影(就是下面的填充)话瞧,可以選擇是否按照什么分布fit,可以選擇kde和hist
sns.distplot(x, bins=20, kde=False, rug=True寝姿,hist=False);
sns.kdeplot(x, bw=.2, label="bw: 0.2"交排,shade=True, cut=0);
sns.distplot(x, kde=False, fit=stats.gamma);
兩個變量關系圖
從最簡單的散點圖開始:
sns.jointplot(x="x", y="y", data=df);
難一點的蜂窩圖
x, y = np.random.multivariate_normal(mean, cov, 1000).T
with sns.axes_style("white"):
sns.jointplot(x=x, y=y, kind="hex", color="k");
以及密度核型圖
sns.jointplot(x="x", y="y", data=df, kind="kde");
等高線圖:
f, ax = plt.subplots(figsize=(6, 6))
sns.kdeplot(df.x, df.y, ax=ax)
sns.rugplot(df.x, color="g", ax=ax)
sns.rugplot(df.y, vertical=True, ax=ax);
還可以玩出花樣:
g = sns.jointplot(x="x", y="y", data=df, kind="kde", color="m")
g.plot_joint(plt.scatter, c="w", s=30, linewidth=1, marker="+")
g.ax_joint.collections[0].set_alpha(0)
g.set_axis_labels("$X$", "$Y$");
pairplot
iris = sns.load_dataset("iris")
sns.pairplot(iris);
g = sns.PairGrid(iris)
g.map_diag(sns.kdeplot)
g.map_offdiag(sns.kdeplot, cmap="Blues_d", n_levels=6);
類別變量
sns.stripplot(x="day", y="total_bill", data=tips);
sns.swarmplot(x="day", y="total_bill", data=tips);
sns.swarmplot(x="total_bill", y="day", hue="time", data=tips);
sns.boxplot(x="day", y="total_bill", hue="time", data=tips);
sns.violinplot(x="total_bill", y="day", hue="time", data=tips);
可以將兩個圖疊加在一起
sns.violinplot(x="day", y="total_bill", data=tips, inner=None)
sns.swarmplot(x="day", y="total_bill", data=tips, color="w", alpha=.5);
對于圖進行基本的統(tǒng)計:
sns.barplot(x="sex", y="survived", hue="class", data=titanic);
sns.countplot(x="deck", data=titanic, palette="Greens_d");
sns.pointplot(x="sex", y="survived", hue="class", data=titanic);
分面圖:
sns.factorplot(x="day", y="total_bill", hue="smoker",
col="time", data=tips, kind="swarm");
線性關系圖
sns.regplot(x="total_bill", y="tip", data=tips);
sns.lmplot(x="total_bill", y="tip", data=tips);