import matplotlib.pyplot as plt
figure.savefig的選項(xiàng)
- filename
- 含有文件路徑的字符串或Python的文件型對(duì)象。圖像格式由文件擴(kuò)展名推斷得出,例如,.pdf推斷出PDF,.png推斷出PNG
(“png”、“pdf”、“svg”、“ps”、“eps”……)
- 含有文件路徑的字符串或Python的文件型對(duì)象。圖像格式由文件擴(kuò)展名推斷得出,例如,.pdf推斷出PDF,.png推斷出PNG
- dpi
- 圖像分辨率(每英寸點(diǎn)數(shù)),默認(rèn)為100
- facecolor
圖像的背景色,默認(rèn)為“w”(白色)
!mkdir "./img"
plt.plot(x,y)
plt.savefig("./img/fig.jpg")
- plt.imread("./source/girl.jpg")
- 圖片數(shù)組化
- plt.imshow(girl)
- 將數(shù)組對(duì)象放入
- axes.set_xscale("log")
- X軸按照l(shuí)og形式顯示
- plt.show()
- 顯示圖片
- figure = img.get_figure()
- 獲取圖片的圖層
- figure.set_size_inches((20,16))
- 設(shè)置圖層的大小
- plt.plot(x,y)
- plot()創(chuàng)建一個(gè)2D線型圖,并且返回該圖的對(duì)象
- lines[1].set_linewidth(5)
- 設(shè)置線寬,圖對(duì)象是一個(gè)數(shù)組,所以[1]
- plt.grid(lw=1,color='red',alpha=0.1)
- 設(shè)置網(wǎng)格線
- lw代表linewidth,線的粗細(xì)
- alpha表示線的明暗程度
- color代表顏色
-
軸面
# 添加子軸面,
#一個(gè)圖層里面可以方多個(gè)圖像,每一個(gè)圖像都是該圖層的一個(gè)子軸面
# 1、取出plt的圖層對(duì)象
figure = plt.figure(figsize=(12,3))
# 2、向圖層中增加子軸面
axes1 = figure.add_subplot(1,3,1)
# 獲取到子軸面對(duì)象,可以把圖像畫在里面
axes1.plot(x,y)
# 三個(gè)參數(shù)分別多少行、多少列、第幾個(gè)(從左到右,從上到下)
# 3、在子軸面中繪制圖像
axes2 = figure.add_subplot(1,3,2)
axes3 = figure.add_subplot(1,3,3)
axes2.plot(x,np.cos(x),color="m",linestyle="-.")
axes3.plot(x,np.tan(x),color='g',linestyle=":")
#加網(wǎng)格
axes1.grid(b=True,c="g",linestyle=":")
axes2.grid(c='r',linestyle="--")
- plt.axis([-15,8,-2,2])
- 參數(shù)是一個(gè)列表,有四個(gè)元素分別代表x軸上下限和y軸上下限
- 'tight'、'off'、'equal'……
- plt.xlim(-4,6)
- plt.ylim(-1,0.5)
- 指定x軸和y軸的坐標(biāo)的上下限
- plt.xlabel("x_value",rotation=0,horizontalalignment="left")
- plt.ylabel("sin(x)",rotation=0,horizontalalignment="center")
- 設(shè)置坐標(biāo)軸標(biāo)簽
- plt.legend(["y=x^2","y=2x","y=cos(x)"])
- 設(shè)置圖例,分別對(duì)應(yīng)三條線
- loc參數(shù)
| 字符串 | 數(shù)值 | 字符串 | 數(shù)值 |
|---|---|---|---|
| best | 0 | center left | 6 |
| upper right | 1 | center right | 7 |
| upper left | 2 | lower center | 8 |
| lower left | 3 | upper center | 9 |
| lower right | 4 | center | 10 |
| right | 5 |
- plt.legend(["y=x^2","y=2x","y=cos(x)"],loc="best")
- plt.legend(loc=(0,0.5),ncol=2)
- 元組第一個(gè)元素代表x方向上圖例方的位置,第二個(gè)元素y方向上圖例的位置
- ncol代表圖例的列數(shù)
設(shè)置plot的風(fēng)格和樣式
axes1.plot(x,y1,ls="--",color="r",marker="o")
-
plt.plot(x,y,color=(0.3,0.4,0.3,0.1))
- rgb alpha
顏色值的方式
- 別名
- color='r'
- 合法的HTML顏色名
- color = 'red'
| 顏色 | 別名 | HTML顏色名 | 顏色 | 別名 | HTML顏色名 |
|---|---|---|---|---|---|
| 藍(lán)色 | b | blue | 綠色 | g | green |
| 紅色 | r | red | 黃色 | y | yellow |
| 青色 | c | cyan | 黑色 | k | black |
| 洋紅色 | m | magenta | 白色 | w | white |
- HTML十六進(jìn)制字符串
- color = '#eeefff'
- 歸一化到[0, 1]的RGB元組
- color = (0.3, 0.3, 0.4)
- plt.subplot(facecolor=(0.2,0.3,0.5))
- 設(shè)置坐標(biāo)軸面的背景顏色
- plt.plot(x,y,facecolor="r")
- plot函數(shù)是用于繪制線形圖的,線形圖沒(méi)有背景顏色
- plt.plot(x,x**3,c=(0.5,0.6,0.3),linestyle = "-.",lw=10)
- plt.plot(x,x**2,dashes=[4,5,8,6])
- dashes里面分別是 長(zhǎng)度 寬度 第二個(gè)長(zhǎng)度,第二個(gè)寬度
線條風(fēng)格設(shè)置
| 線條風(fēng)格 | 描述 | 線條風(fēng)格 | 描述 |
|---|---|---|---|
| '-' | 實(shí)線 | ':' | 虛線 |
| '--' | 破折線 | 'steps' | 階梯線 |
| '-.' | 點(diǎn)劃線 | 'None' / ',' | 什么都不畫 |
- marker參數(shù)
- plt.plot([1,2,4,6,7,9],[1,1,4,9,10,20],marker="4")
| 標(biāo)記 | 描述 | 標(biāo)記 | 描述 |
|---|---|---|---|
| '1' | 一角朝下的三腳架 | '3' | 一角朝左的三腳架 |
| '2' | 一角朝上的三腳架 | '4' | 一角朝右的三腳架 |
- plt.plot(x,y,marker="o",markersize=10)
- markersize代表點(diǎn)的大小
| 標(biāo)記 | 描述 | 標(biāo)記 | 描述 |
| :-------------: |:-----------:| :----:| :-----:|
| 's' | 正方形 | 'p' | 五邊形 |
| 'h' | 六邊形1 | 'H' | 六邊形2 |
| '8' | 八邊形 |
- markersize代表點(diǎn)的大小
| 標(biāo)記 | 描述 | 標(biāo)記 | 描述 |
|---|---|---|---|
| '.' | 點(diǎn) | 'x' | X |
| '*' | 星號(hào) | '+' | 加號(hào) |
| ',' | 像素 |
| 標(biāo)記 | 描述 | 標(biāo)記 | 描述 |
|---|---|---|---|
| 'o' | 圓圈 | 'D' | 菱形 |
| 'd' | 小菱形 | '','None',' ',None | 無(wú) |
| 標(biāo)記 | 描述 | 標(biāo)記 | 描述 |
|---|---|---|---|
| '_' | 水平線 | '|' | 水平線 |
- 更多點(diǎn)線設(shè)置
- plt.plot(x,y,"-.g",x,x2,"--or",x,x2,"--",x,x)
- plt.plot(x,x**2,c='r',ls='-.',marker='o',markeredgecolor='g',
markerfacecolor='m',markeredgewidth=3,markersize=10) - plt.plot(x,x*2,ls="-.",x,x4,marker="o")
- 屬性設(shè)置不能把屬性?shī)A雜在曲線之間,會(huì)報(bào)錯(cuò)
- line, = plt.plot(x,y)
- plt.setp(line,marker="*",ls="-.",c="g")
- setp方法傳參
- setter方法
lines = plt.plot(x,y,x,x**2)
# 通過(guò)setter方法對(duì)屬性進(jìn)行設(shè)置
lines[0].set_color("r")
lines[0].set_marker(">")
lines[1].set_ls("-.")
lines[1].set_lw(10)
| 參數(shù) | 描述 | 參數(shù) | 描述 |
|---|---|---|---|
| color或c | 線的顏色 | linestyle或ls | 線型 |
| linewidth或lw | 線寬 | marker | 點(diǎn)型 |
| markeredgecolor | 點(diǎn)邊緣的顏色 | markeredgewidth | 點(diǎn)邊緣的寬度 |
| markerfacecolor | 點(diǎn)內(nèi)部的顏色 | markersize | 點(diǎn)的大小 |
X、Y軸坐標(biāo)刻度
x = np.linspace(-5,5,50)
y = np.sin(x)
plt.plot(x,y,c='r')
# 設(shè)置x軸坐標(biāo)的標(biāo)記
plt.xticks(np.linspace(-np.pi,np.pi,5),
("-pi","-pi/2","0","pi/2","pi"),size=20,rotation=60)
# y軸留三個(gè)
plt.yticks([-1,0,1],["min",0,'max'])
面向?qū)ο蠓椒ㄔO(shè)置刻度
# 坐標(biāo)標(biāo)簽與刻度屬于圖層面板
figure = plt.figure(figsize=(12,5))
axes = figure.add_subplot(111)
axes.plot(x,y,c="m")
axes.set_xticks(np.linspace(-np.pi,np.pi,5)) # 這個(gè)方法設(shè)置下標(biāo)的位置
axes.set_xticklabels(["-pi","-pi/2",0,"pi/2","pi"],size=10)
- LaTex語(yǔ)法,用 ππ 等表達(dá)式在圖表上寫上希臘字母
plt.plot(x,y)
plt.xticks(np.linspace(-np.pi,np.pi,5),
["-$\pi$","-$\pi$/2",0,"$\pi$/2","$\pi$"])
其他2D圖形
直方圖
【直方圖的參數(shù)只有一個(gè)x!??!不像條形圖需要傳入x,y】
hist()的參數(shù)
- bins
可以是一個(gè)bin數(shù)量的整數(shù)值,也可以是表示bin的一個(gè)序列。默認(rèn)值為10 - normed
如果值為True,直方圖的值將進(jìn)行歸一化處理,形成概率密度,默認(rèn)值為False - color
指定直方圖的顏色??梢允菃我活伾祷蝾伾男蛄?。如果指定了多個(gè)數(shù)據(jù)集合,顏色序列將會(huì)設(shè)置為相同的順序。如果未指定,將會(huì)使用一個(gè)默認(rèn)的線條顏色 - orientation
通過(guò)設(shè)置orientation為horizontal創(chuàng)建水平直方圖。默認(rèn)值為vertical
x = np.random.randint(0,10,size=100)
print(x)
plt.hist(x,bins=20,normed=True,color='r',orientation="vertical")
# bins參數(shù)代表是劃分多少個(gè)區(qū)間,normed參數(shù)代表是否歸一化
條形圖
【條形圖有兩個(gè)參數(shù)x,y!】
bar()、barh()
- plt.bar(x,x,width=0.1)
- 條形圖適合樣本量比較小的統(tǒng)計(jì)量,如果比較大會(huì)自動(dòng)選取某些代表點(diǎn)
- barh()為水平的條形圖
餅圖
【餅圖也只有一個(gè)參數(shù)x!】
- pie()
- 餅圖適合展示各部分占總體的比例,條形圖適合比較各部分的大小
- 普通各部分占滿餅圖
- 普通未占滿餅圖
labels = ["China","USA","EU","Japan","UK","France","Others"]
data = np.array([0.12,0.18,0.15,0.06,0.03,0.025,0.465])
plt.pie(data,labels=labels,labeldistance=1,autopct="%0.2f%%",
pctdistance=0.8,explode=[0.2,0.2,0,0,0.5,0.1,0.1],shadow=True,
startangle=180
)
餅圖陰影、分裂等屬性設(shè)置
- labels參數(shù)設(shè)置每一塊的標(biāo)簽;labeldistance參數(shù)設(shè)置標(biāo)簽距離圓心的距離(比例值)
- autopct參數(shù)設(shè)置比例值的顯示格式(%1.1f%%);pctdistance參數(shù)設(shè)置比例值文字距離圓心的距離
- explode參數(shù)設(shè)置每一塊頂點(diǎn)距圓形的長(zhǎng)度(比例值);colors參數(shù)設(shè)置每一塊的顏色;
- shadow參數(shù)為布爾值,設(shè)置是否繪制陰影
- startangle設(shè)置旋轉(zhuǎn)角度
散點(diǎn)圖
【散點(diǎn)圖需要兩個(gè)參數(shù)x,y,但此時(shí)x不是表示x軸的刻度,而是每個(gè)點(diǎn)的橫坐標(biāo)!】
- scatter()
x = np.random.randn(1000)
y = np.random.randn(1000)
# 隨機(jī)生成1000中顏色
colors = np.random.rand(3000).reshape((1000,3))
# 隨機(jī)生成1000個(gè)大小
size = np.random.randint(1,100,size=1000)
plt.scatter(x,y,color=colors,s=size,marker="d")
圖形內(nèi)的文字、注釋、箭頭
控制文字屬性的方法:
| Pyplot函數(shù) | API方法 | 描述 |
|---|---|---|
| text() | mpl.axes.Axes.text() | 在Axes對(duì)象的任意位置添加文字 |
| xlabel() | mpl.axes.Axes.set_xlabel() | 為X軸添加標(biāo)簽 |
| ylabel() | mpl.axes.Axes.set_ylabel() | 為Y軸添加標(biāo)簽 |
| title() | mpl.axes.Axes.set_title() | 為Axes對(duì)象添加標(biāo)題 |
| legend() | mpl.axes.Axes.legend() | 為Axes對(duì)象添加圖例 |
| figtext() | mpl.figure.Figure.text() | 在Figure對(duì)象的任意位置添加文字 |
| suptitle() | mpl.figure.Figure.suptitle() | 為Figure對(duì)象添加中心化的標(biāo)題 |
| annnotate() | mpl.axes.Axes.annotate() | 為Axes對(duì)象添加注釋(箭頭可選) |
所有的方法會(huì)返回一個(gè)matplotlib.text.Text對(duì)象
- plt.text(2,2,"xxx",size=20)
plt.figtext(1,0.5,"sss")#相對(duì)位置 - annotate(text,xy=(tx0,ty0),xytext=(tx1,ty1),arrowprops=dict(arrowstyle="->",connectionstyle="arc3"))
注釋
annotate()
xy參數(shù)設(shè)置箭頭指示的位置,xytext參數(shù)設(shè)置注釋文字的位置
arrowprops參數(shù)以字典的形式設(shè)置箭頭的樣式
width參數(shù)設(shè)置箭頭長(zhǎng)方形部分的寬度,headlength參數(shù)設(shè)置箭頭尖端的長(zhǎng)度,
headwidth參數(shù)設(shè)置箭頭尖端底部的寬度,
facecolor設(shè)置箭頭顏色
shrink參數(shù)設(shè)置箭頭頂點(diǎn)、尾部與指示點(diǎn)、注釋文字的距離(比例值)
3D圖
from mpl_toolkits.mplot3d import Axes3D
ax = plt.subplot(projection="3d")
ax.scatter3D(samples["2006世界杯"],samples["2010世界杯"],samples["2007亞洲杯"],c=y_)
centers = km.cluster_centers_
ax.scatter3D(centers[:,0],centers[:,1],centers[:,2],c='r')