Matplotlib基礎使用

matplotlib

1、Matplotlib基礎知識

Matplotlib中的基本圖表包括的元素python

  • x軸和y軸 axis
    水平和垂直的軸線dom

  • x軸和y軸刻度 tick
    刻度標示座標軸的分隔,包括最小刻度和最大刻度svg

  • x軸和y軸刻度標籤 tick label
    表示特定座標軸的值函數

  • 繪圖區域(座標系) axes
    實際繪圖的區域字體

  • 座標系標題 title
    實際繪圖的區域spa

  • 軸標籤 xlabel ylabel
    實際繪圖的區域3d

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import Series,DataFrame

%matplotlib inline   # 魔法指令

包含單條曲線的圖

  • 注意:y,x軸的值必須爲數字
x=[1,2,3,4,5]
y=[2,4,6,8,10]
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x2f5e4d8f160>]

  • 繪製拋物線
x = np.linspace(-np.pi,np.pi,num=10)
y = x**2
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x2f5e4e35748>]

  • 繪製正弦曲線圖
x = x
y = np.sin(x)
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x2f5e4e9ab38>]

包含多個曲線的圖

一、連續調用屢次plot函數code

plt.plot(x,y)
plt.plot(x-1,y+2)
[<matplotlib.lines.Line2D at 0x2f5e4eb78d0>]

plt.plot(x,y,x+1,y-1)
[<matplotlib.lines.Line2D at 0x2f5e51832e8>,
 <matplotlib.lines.Line2D at 0x2f5e51834a8>]

二、也能夠在一個plot函數中傳入多對X,Y值,在一個圖中繪製多個曲線orm

將多個曲線圖繪製在一個table區域中:對象形式建立表圖

  • a=plt.subplot(row,col,loc) 建立曲線圖
  • a.plot(x,y) 繪製曲線圖
ax1 = plt.subplot(2,2,1)
ax1.plot(x,y)

ax2 = plt.subplot(222)
ax2.plot(x+1,y-2)

ax3 = plt.subplot(223)
ax3.plot(x+3,y-1)

ax4 = plt.subplot(224)
ax4.plot(x**2,y-2)
[<matplotlib.lines.Line2D at 0x2f5e6462208>]

座標軸界限

axis方法:設置x,y軸刻度值的範圍對象

  • plt.axis([xmin,xmax,ymin,ymax])
plt.plot(x,y)
plt.axis([-6,6,-2,2])
[-6, 6, -2, 2]

plt.axis('off')

  • 關閉座標軸
plt.plot(x,y)
plt.axis('off')
(-3.4557519189487724,
 3.4557519189487724,
 -1.0832885283134288,
 1.083288528313429)

設置畫布比例:plt.figure(figsize=(a,b)) a:x刻度比例 b:y刻度比例 (2:1)表示x刻度顯示爲y刻度顯示的2倍

plt.figure(figsize=(16,8))
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x2f5e63b6400>]

座標軸標籤

  • s 標籤內容
  • color 標籤顏色
  • fontsize 字體大小
  • rotation 旋轉角度

  • plt的xlabel方法和ylabel方法 title方法

plt.plot(x,y)
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Title')
Text(0.5,1,'Title')

圖例

legend方法

兩種傳參方法:

  • 分別在plot函數中增長label參數,再調用plt.legend()方法顯示
  • 直接在legend方法中傳入字符串列表
plt.plot(x,y,label='xian_1')
plt.plot(x-1,y+3,label='xian_2')
plt.legend()
<matplotlib.legend.Legend at 0x2f5e66057b8>

legend的參數
  • loc參數
  • loc參數用於設置圖例標籤的位置,通常在legend函數內
  • matplotlib已經預約義好幾種數字表示的位置
plt.plot(x,y,label='xian_1')
plt.plot(x-1,y+3,label='xian_2')
plt.legend(loc=3)
<matplotlib.legend.Legend at 0x2f5e68f6c88>

字符串 數值 字符串 數值
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
  • ncol參數: ncol控制圖例中有幾列,在legend中設置ncol
plt.plot(x,y,label='xian_1')
plt.plot(x-1,y+3,label='xian_2')
plt.legend(loc=3,ncol=2)
<matplotlib.legend.Legend at 0x2f5e6ab4a90>

保存圖片

使用figure對象的savefig函數來保存圖片

fig = plt.figure()---必須放置在繪圖操做以前

figure.savefig的參數選項

  • filename
    含有文件路徑的字符串或Python的文件型對象。圖像格式由文件擴展名推斷得出,例如,.pdf推斷出PDF,.png推斷出PNG
    (「png」、「pdf」、「svg」、「ps」、「eps」……)
  • dpi
    圖像分辨率(每英寸點數),默認爲100
  • facecolor ,打開保存圖片查看
    圖像的背景色,默認爲「w」(白色)
fig = plt.figure()

plt.plot(x,y,label='temp')
plt.plot(x-1,y+3,label='dist')
plt.legend(loc=3,ncol=2)

fig.savefig('./123.png',dpi=300)

設置plot的風格和樣式

plot語句中支持除X,Y之外的參數,以字符串形式存在,來控制顏色、線型、點型等要素,語法形式爲:
plt.plot(X, Y, 'format', ...)

顏色

參數color或c

plt.plot(x,y,c='red',alpha=0.5,ls='steps',lw=3)
[<matplotlib.lines.Line2D at 0x2f5e6a4c668>]

顏色值的方式
  • 別名
    • color='r'
  • 合法的HTML顏色名

    • color = 'red'
顏色 別名 HTML顏色名 顏色 別名 HTML顏色名
藍色 b blue 綠色 g green
紅色 r red 黃色 y yellow
青色 c cyan 黑色 k black
洋紅色 m magenta 白色 w white
  • HTML十六進制字符串
    • color = '#eeefff'
  • 歸一化到[0, 1]的RGB元組
    • color = (0.3, 0.3, 0.4)
透明度

alpha參數

線型

參數linestyle或ls

線條風格 描述 線條風格 描述
'-' 實線 ':' 虛線
'--' 破折線 'steps' 階梯線
'-.' 點劃線 'None' / ',' 什麼都不畫
線寬

linewidth或lw參數

點型
  • marker 設置點形
  • markersize 設置點形大小
標記 描述 標記 描述
's' 正方形 'p' 五邊形
'h' 六邊形1 'H' 六邊形2
'8' 八邊形
標記 描述 標記 描述
'.' 'x' X
'*' 星號 '+' 加號
',' 像素
標記 描述 標記 描述
'o' 圓圈 'D' 菱形
'd' 小菱形 '','None',' ',None
標記 描述 標記 描述
'1' 一角朝下的三腳架 '3' 一角朝左的三腳架
'2' 一角朝上的三腳架 '4' 一角朝右的三腳架
plt.plot(x,y,marker='s')
[<matplotlib.lines.Line2D at 0x2f5e6b87dd8>]

# 繪製線      plt.plot(x1,y1,x2,y2)
# 網格線      plt.grid(True)  axes.grid(color,ls,lw,alpha)
# 獲取座標系  plt.subplot(n1,n2,n3)
# 座標軸標籤  plt.xlabel() plt.ylabel()
# 座標系標題  plt.title()
# 圖例        plt.legend([names],ncol=2,loc=1)  plt.plot(label='name')
# 線風格      --  -. : None  step
# 圖片保存    figure.savefig()
# 點的設置    marker markersize markerfacecolor markeredgecolor\width
# 座標軸刻度  plt.xticks(刻度列表,刻度標籤列表) plt.yticks()
#             axes.set_xticks(刻度列表) axes.set_xticklabels(刻度標籤列表)

2、2D圖形

直方圖

  • 是一個特殊的柱狀圖,又叫作密度圖。

【直方圖的參數只有一個x!!!不像條形圖須要傳入x,y】

plt.hist()的參數

  • bins
    直方圖的柱數,可選項,默認爲10
  • color
    指定直方圖的顏色。能夠是單一顏色值或顏色的序列。若是指定了多個數據集合,例如DataFrame對象,顏色序列將會設置爲相同的順序。若是未指定,將會使用一個默認的線條顏色
  • orientation
    經過設置orientation爲horizontal建立水平直方圖。默認值爲vertical
data = [1,2,3,3,4,2,5]
plt.hist(data,bins=10)
(array([1., 0., 2., 0., 0., 2., 0., 1., 0., 1.]),
 array([1. , 1.4, 1.8, 2.2, 2.6, 3. , 3.4, 3.8, 4.2, 4.6, 5. ]),
 <a list of 10 Patch objects>)

返回值 :

1: 直方圖向量,是否歸一化由參數normed設定

2: 返回各個bin的區間範圍

3: 返回每一個bin裏面包含的數據,是一個list

條形圖:plt.bar()

  • 參數:第一個參數是索引。第二個參數是數據值。第三個參數是條形的寬度

-【條形圖有兩個參數x,y】

  • width 縱向設置條形寬度
  • height 橫向設置條形高度

bar()、barh()

x = [1,2,3,4,5]
y = [2,4,6,8,10]
plt.bar(x,y)
<Container object of 5 artists>

plt.barh(x,y)
<Container object of 5 artists>

餅圖

【餅圖也只有一個參數x】

pie()
餅圖適合展現各部分佔整體的比例,條形圖適合比較各部分的大小

普通各部分佔滿餅圖

plt.pie([1,3,5])
([<matplotlib.patches.Wedge at 0x2f5e6d46198>,
  <matplotlib.patches.Wedge at 0x2f5e6d46668>,
  <matplotlib.patches.Wedge at 0x2f5e6d46ba8>],
 [Text(1.03366,0.376222,''),
  Text(-0.191013,1.08329,''),
  Text(-0.191013,-1.08329,'')])

普通未佔滿餅圖:小數/比例

plt.pie([0.2,0.3,0.4])
([<matplotlib.patches.Wedge at 0x2f5e6d8d6d8>,
  <matplotlib.patches.Wedge at 0x2f5e6d8dba8>,
  <matplotlib.patches.Wedge at 0x2f5e6d95128>],
 [Text(0.889919,0.646564,''),
  Text(-0.646564,0.889919,''),
  Text(-0.339919,-1.04616,'')])

餅圖陰影、分裂等屬性設置

labels參數設置每一塊的標籤;

labeldistance參數設置標籤距離圓心的距離(比例值)

autopct參數設置比例值小數保留位(%.3f%%);

pctdistance參數設置比例值文字距離圓心的距離

explode參數設置每一塊頂點距圓心的長度(比例值,列表);

colors參數設置每一塊的顏色(列表);

shadow參數爲布爾值,設置是否繪製陰影

startangle參數設置餅圖起始角度

arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'])
([<matplotlib.patches.Wedge at 0x2f5e7da2f28>,
  <matplotlib.patches.Wedge at 0x2f5e7daa438>,
  <matplotlib.patches.Wedge at 0x2f5e7daa978>,
  <matplotlib.patches.Wedge at 0x2f5e7daaeb8>],
 [Text(0.996424,0.465981,'a'),
  Text(-0.195798,1.08243,'b'),
  Text(-0.830021,-0.721848,'c'),
  Text(0.910034,-0.61793,'d')])

# labeldistance參數設置標籤距離圓心的距離(比例值)
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3)
([<matplotlib.patches.Wedge at 0x2f5e7dedb38>,
  <matplotlib.patches.Wedge at 0x2f5e7dedf98>,
  <matplotlib.patches.Wedge at 0x2f5e7df7518>,
  <matplotlib.patches.Wedge at 0x2f5e7df7a58>],
 [Text(0.271752,0.127086,'a'),
  Text(-0.0533994,0.295209,'b'),
  Text(-0.226369,-0.196868,'c'),
  Text(0.248191,-0.168526,'d')])

# autopct參數設置比例值小數保留位(%.3f%%);
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3,autopct='%.5f%%')
([<matplotlib.patches.Wedge at 0x2f5e7e3f668>,
  <matplotlib.patches.Wedge at 0x2f5e7e3fd68>,
  <matplotlib.patches.Wedge at 0x2f5e7e47518>,
  <matplotlib.patches.Wedge at 0x2f5e7e47c88>],
 [Text(0.271752,0.127086,'a'),
  Text(-0.0533994,0.295209,'b'),
  Text(-0.226369,-0.196868,'c'),
  Text(0.248191,-0.168526,'d')],
 [Text(0.543504,0.254171,'13.92405%'),
  Text(-0.106799,0.590419,'27.84810%'),
  Text(-0.452739,-0.393735,'39.24051%'),
  Text(0.496382,-0.337053,'18.98734%')])

# explode參數設置每一塊頂點距圓心的長度(比例值,列表);
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3,shadow=True,explode=[0.2,0.3,0.2,0.4])
([<matplotlib.patches.Wedge at 0x2f5e7e8ca90>,
  <matplotlib.patches.Wedge at 0x2f5e7e95240>,
  <matplotlib.patches.Wedge at 0x2f5e7e95a58>,
  <matplotlib.patches.Wedge at 0x2f5e7e9d2b0>],
 [Text(0.45292,0.21181,'a'),
  Text(-0.106799,0.590419,'b'),
  Text(-0.377282,-0.328113,'c'),
  Text(0.579113,-0.393228,'d')])

%m.nf
m 佔位
n 小數點後保留幾位
f 是以float格式輸出

散點圖:因變量隨自變量而變化的大體趨勢

【散點圖須要兩個參數x,y,但此時x不是表示x軸的刻度,而是每一個點的橫座標!】

scatter()

plt.scatter(x,y)
<matplotlib.collections.PathCollection at 0x2f5e7edbe10>

plt.scatter(x,y,marker='d',c="rbgy") 設置不一樣的散點顏色

x = np.random.random(size=(30,))
y = np.random.random(size=(30,))
plt.scatter(x,y)
<matplotlib.collections.PathCollection at 0x2f5e7f519e8>

相關文章
相關標籤/搜索