日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数据可视化组队学习:《Task02 - 艺术画笔见乾坤》笔记

發布時間:2025/3/15 编程问答 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据可视化组队学习:《Task02 - 艺术画笔见乾坤》笔记 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 前言
  • 1 概述
    • 1.1 matplotlib的使用邏輯
    • 1.2 matplotlib的三層api
    • 1.3 Artist類的結構
    • 1.4 matplotlib標準用法
  • 2 自定義你的Artist對象
    • 2.1 Artist屬性
    • 2.2 屬性調用的方式
  • 3 基本元素 - primitives
    • 3.1 Line2D
      • 3.1.1 如何設置Line2D的屬性
      • 3.1.2 繪制Line2D
      • 3.1.3 errorbar繪制誤差折線圖
    • 3.2 patches
      • 3.2.1 繪制Rectangle-矩形
      • 3.2.3 繪制Polygon-多邊形
      • 3.2.3 繪制Wedge-契形
    • 3.3 collections-繪制一組對象的集合
      • 3.3.1 scatter繪制散點圖
    • 3.4 images
  • 4 對象容器 - Object container
    • 4.1 Figure容器
    • 4.2 Axes容器
      • 4.2.1 Subplot和Axes的區別
      • 4.3 Axis容器
    • 4.4 Tick容器
  • 作業
    • 思考題
    • 繪圖題

前言

本文為數據可視化組隊學習:《Task02 - 藝術畫筆見乾坤》筆記。


1 概述

1.1 matplotlib的使用邏輯

跟人類繪圖一樣,用matplotlib也是一樣的步驟:

  • 準備一塊畫布或畫紙
  • 準備好顏料、畫筆等制圖工具
  • 作畫
  • 1.2 matplotlib的三層api

    就如房子一般,是從地基一直往屋頂建的,在matplotlib中,也有類似的層次結構:

  • matplotlib.backend_bases.FigureCanvas
    代表了繪圖區,所有的圖像都是在繪圖區完成的
  • matplotlib.backend_bases.Renderer
    代表了渲染器,可以近似理解為畫筆,控制如何在 FigureCanvas 上畫圖。
  • matplotlib.artist.Artist
    代表了具體的圖表組件,即調用了Renderer的接口在Canvas上作圖。
  • 1、2 處理程序和計算機的底層交互的事項,3 Artist就是具體的調用接口來做出我們想要的圖,比如圖形、文本、線條的設定。所以通常來說,我們95%的時間,都是用來和 matplotlib.artist.Artist 類打交道的。

    1.3 Artist類的結構

    其中圖形figure、坐標系Axes和坐標軸Axis的關系如下圖所示:

    ▲ 圖形figure、坐標系Axes和坐標軸Axis的關系

    1.4 matplotlib標準用法

    由圖形figure、坐標系Axes和坐標軸Axis的關系,可以得到matplotlib畫圖的標準方法,還是以建房子為例,從地基到房頂建造:

  • 創建一個Figure實例
  • 使用Figure實例創建一個或者多個Axes或Subplot實例
  • 使用Axes實例的輔助方法來創建primitive
  • import matplotlib.pyplot as plt import numpy as np# step 1 # 我們用 matplotlib.pyplot.figure() 創建了一個Figure實例 fig = plt.figure()# step 2 # 然后用Figure實例創建了一個兩行一列(即可以有兩個subplot)的繪圖區,并同時在第一個位置創建了一個subplot ax = fig.add_subplot(2, 1, 1) # two rows, one column, first plot# step 3 # 然后用Axes實例的方法畫了一條曲線 t = np.arange(0.0, 1.0, 0.01) s = np.sin(2*np.pi*t) line, = ax.plot(t, s, color='blue', lw=2)

    2 自定義你的Artist對象

    2.1 Artist屬性

    在圖形中的每一個元素都對應著一個matplotlib Artist,且都有其對應的配置屬性列表。
    每個matplotlib Artist都有以下常用屬性:

  • .alpha屬性:透明度。值為0—1之間的浮點數
  • .axes屬性:返回這個Artist所屬的axes,可能為None
  • .figure屬性:該Artist所屬的Figure,可能為None
  • .label:一個text label
  • .visible:布爾值,控制Artist是否繪制
  • 補充,完整屬性列表:

    PropertyDescription
    alphaThe transparency - a scalar from 0-1
    animatedA boolean that is used to facilitate animated drawing
    axesThe axes that the Artist lives in, possibly None
    clip_boxThe bounding box that clips the Artist
    clip_onWhether clipping is enabled
    clip_pathThe path the artist is clipped to
    containsA picking function to test whether the artist contains the pick point
    figureThe figure instance the artist lives in, possibly None
    labelA text label (e.g., for auto-labeling)
    pickerA python object that controls object picking
    transformThe transformation
    visibleA boolean whether the artist should be drawn
    zorderA number which determines the drawing order
    rasterizedBoolean; Turns vectors into raster graphics (for compression & eps transparency)

    特別有Figure、Axes本身具有一個Rectangle,使用 Figure.patch 和 Axes.patch 可以查看:

    # .patch plt.figure().patch plt.axes().patch

    2.2 屬性調用的方式

    既然每個Artist對象都有屬性,那么該如何去查看和修改這些屬性呢?

    Artist對象的所有屬性都通過相應的 get_* 和 set_* 函數進行讀寫。

  • 例如下面的語句將alpha屬性設置為當前值的一半:
  • a = o.get_alpha() o.set_alpha(0.5*a)
  • 如果想一次設置多個屬性,也可以用set方法:
  • o.set(alpha=0.5, zorder=2)
  • 可以使用 matplotlib.artist.getp(o,“alpha”) 來獲取屬性,如果指定屬性名,則返回對象的該屬性值;如果不指定屬性名,則返回對象的所有的屬性和值。
  • import matplotlib # Figure rectangle的屬性 matplotlib.artist.getp(fig.patch) agg_filter = Nonealpha = Noneanimated = Falseantialiased or aa = Falsebbox = Bbox(x0=0.0, y0=0.0, x1=1.0, y1=1.0)capstyle = buttchildren = []clip_box = Noneclip_on = Trueclip_path = Nonecontains = Nonedata_transform = BboxTransformTo( TransformedBbox( Bbox...edgecolor or ec = (1.0, 1.0, 1.0, 0.0)extents = Bbox(x0=0.0, y0=0.0, x1=432.0, y1=288.0)facecolor or fc = (1.0, 1.0, 1.0, 0.0)figure = Figure(432x288)fill = Truegid = Nonehatch = Noneheight = 1in_layout = Falsejoinstyle = miterlabel = linestyle or ls = solidlinewidth or lw = 0.0patch_transform = CompositeGenericTransform( BboxTransformTo( ...path = Path(array([[0., 0.], [1., 0.], [1.,...path_effects = []picker = Nonerasterized = Nonesketch_params = Nonesnap = Nonetransform = CompositeGenericTransform( CompositeGenericTra...transformed_clip_path_and_affine = (None, None)url = Noneverts = [[ 0. 0.] [432. 0.] [432. 288.] [ 0. 288....visible = Truewidth = 1window_extent = Bbox(x0=0.0, y0=0.0, x1=432.0, y1=288.0)x = 0xy = (0, 0)y = 0zorder = 1

    3 基本元素 - primitives

    3.1 Line2D

    在matplotlib中曲線的繪制,主要是通過類 matplotlib.lines.Line2D 來完成的。
    它的基類: matplotlib.artist.Artist

    3.1.1 如何設置Line2D的屬性

    有三種方法。

  • 直接在plot()函數中設置
  • import matplotlib.pyplot as plt x = range(0,5) y = [2,5,7,8,10] plt.plot(x,y, linewidth=10) # 設置線的粗細參數為10
  • 通過獲得線對象,對線對象進行設置
  • x = range(0,5) y = [2,5,7,8,10] line, = plt.plot(x, y, '-') line.set_antialiased(False) # 關閉抗鋸齒功能
  • 獲得線屬性,使用setp()函數設置
  • x = range(0,5) y = [2,5,7,8,10] lines = plt.plot(x, y) plt.setp(lines, color='r', linewidth=10)

    3.1.2 繪制Line2D

    繪制直線line常用的方法有兩種。

    • pyplot方法繪制
    • Line2D對象繪制

    常用參數:

    • xdata:需要繪制的line中點的在x軸上的取值,若忽略,則默認為range(1,len(ydata)+1)
    • ydata:需要繪制的line中點的在y軸上的取值
    • linewidth:線條的寬度
    • linestyle:線型
    • color:線條的顏色
    • marker:點的標記,詳細可參考markers API 1
    • markersize:標記的size
    • pyplot方法繪制
      這種方法更加簡便。
    import matplotlib.pyplot as plt x = range(0,5) y = [2,5,7,8,10] plt.plot(x,y)
    • Line2D對象繪制
      這種方法完美地詮釋了matplotlib畫圖的figure→axes→axis結構。
    import matplotlib.pyplot as plt from matplotlib.lines import Line2D # figure fig = plt.figure()# axes ax = fig.add_subplot(111)x = range(0,5) y = [2,5,7,8,10] line = Line2D(x, y) ax.add_line(line)# axis ax.set_xlim(min(x), max(x)) ax.set_ylim(min(y), max(y))plt.show()

    上述代碼也可用下面的代替:

    import matplotlib.pyplot as plt from matplotlib.lines import Line2D fig = plt.figure() ax = fig.add_subplot(111) # 1×1網格,第1子圖x = range(0,5) y = [2,5,7,8,10] line = Line2D(x, y) ax.add_line(line)ax.set(xlim=(min(x), max(x)), ylim=(min(y), max(y)))plt.show()

    3.1.3 errorbar繪制誤差折線圖

    構造方法如下:

    matplotlib.pyplot.errorbar(x, y, yerr=None, xerr=None, fmt=’’, ecolor=None, elinewidth=None, capsize=None, barsabove=False, lolims=False, uplims=False, xlolims=False, xuplims=False, errorevery=1, capthick=None, *, data=None, **kwargs)

    主要參數:

    • x:需要繪制的line中點的在x軸上的取值
    • y:需要繪制的line中點的在y軸上的取值
    • yerr:指定y軸水平的誤差
    • xerr:指定x軸水平的誤差
    • fmt:指定折線圖中某個點的顏色,形狀,線條風格,例如‘co–’
    • ecolor:指定error bar的顏色
    • elinewidth:指定error bar的線條寬度

    errorbar的基類是matplotlib.pyplot,所以不需要plot.show().

    import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = 2.5 * np.sin(x / 20 * np.pi) yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)')

    加個 linewidth=10, color='r':

    import numpy as np import matplotlib.pyplot as plt x = np.arange(10) y = 2.5 * np.sin(x / 20 * np.pi) yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 5,linewidth=10,color='r', yerr=yerr, label='both limits (default)') plt.legend() # 輸出label

    3.2 patches

    matplotlib.patches.Patch類是二維圖形類。它的基類是matplotlib.artist.Artist。

    3.2.1 繪制Rectangle-矩形

    Rectangle矩形類在官網中的定義是: 通過錨點xy及其寬度和高度生成。

    Rectangle本身的主要比較簡單,即xy控制錨點,width和height分別控制寬和高。它的構造函數:

    class matplotlib.patches.Rectangle(xy, width, height, angle=0.0, **kwargs)

    在實際中最常見的矩形圖是hist直方圖bar條形圖

  • hist-直方圖
    兩種繪制方法:
    • 使用plt.hist繪制
    • 使用Rectangle矩形類繪制直方圖
    • 使用plt.hist繪制
      非常簡便。

    matplotlib.pyplot.hist(x,bins=None,range=None, density=None, bottom=None, histtype=‘bar’, align=‘mid’, log=False, color=None, label=None, stacked=False, normed=None)

    常用的參數:

    • x: 數據集,最終的直方圖將對數據集進行統計
    • bins: 統計的區間分布
    • range: tuple, 顯示的區間,range在沒有給出bins時生效
    • density: bool,默認為false,顯示的是頻數統計結果,為True則顯示頻率統計結果,這里需要注意,頻率統計結果=區間數目/(總數*區間寬度),和>- normed效果一致,官方推薦使用density
    • histtype: 可選{‘bar’, ‘barstacked’, ‘step’, ‘stepfilled’}之一,默認為bar,推薦使用默認配置,step使用的是梯狀,stepfilled則會對梯狀內部進行填充,效果與bar類似
    • align: 可選{‘left’, ‘mid’, ‘right’}之一,默認為’mid’,控制柱狀圖的水平分布,left或者right,會有部分空白區域,推薦使用默認
    • log: bool,默認False,即y坐標軸是否選擇指數刻度
    • stacked: bool,默認為False,是否為堆積狀圖
    import matplotlib.pyplot as plt import numpy as np # 落入每個范圍的x數據集中的數據個數 x=np.random.randint(0,100,100) #生成[0-100)之間的100個數據,即數據集 bins=np.arange(0,101,10) #設置連續的邊界值,即直方圖的分布區間[0,10),[10,20)... plt.hist(x,bins,color='fuchsia',alpha=0.5)#alpha設置透明度,0為完全透明 plt.xlabel('scores') plt.ylabel('count') plt.xlim(0,100)#設置x軸分布范圍 plt.show() import matplotlib.pyplot as plt import numpy as np # 落入每個范圍的x數據集中的數據個數 x=np.random.randint(0,100,100) #生成[0-100)之間的100個數據,即數據集 bins=np.arange(0,101,10) #設置連續的邊界值,即直方圖的分布區間[0,10),[10,20)... plt.hist(x,bins,color='fuchsia',alpha=0.5)#alpha設置透明度,0為完全透明 plt.xlabel('scores') plt.ylabel('count') # plt.xlim(0,100) plt.xlim(0,200)#設置x軸分布范圍
    • 使用Rectangle矩形類繪制直方圖
      個人感覺比較麻煩。
    import pandas as pd import re df = pd.DataFrame(columns = ['data']) df.loc[:,'data'] = x df['fenzu'] = pd.cut(df['data'], bins=bins, right = False,include_lowest=True)df_cnt = df['fenzu'].value_counts().reset_index() df_cnt.loc[:,'mini'] = df_cnt['index'].astype(str).map(lambda x:re.findall('\[(.*)\,',x)[0]).astype(int) df_cnt.loc[:,'maxi'] = df_cnt['index'].astype(str).map(lambda x:re.findall('\,(.*)\)',x)[0]).astype(int) df_cnt.loc[:,'width'] = df_cnt['maxi']- df_cnt['mini'] df_cnt.sort_values('mini',ascending = True,inplace = True) df_cnt.reset_index(inplace = True,drop = True)#用Rectangle把hist繪制出來 import matplotlib.pyplot as pltfig = plt.figure() ax1 = fig.add_subplot(111) #rect1 = plt.Rectangle((0,0),10,10) #ax1.add_patch(rect)#ax2 = fig.add_subplot(212) for i in df_cnt.index:rect = plt.Rectangle((df_cnt.loc[i,'mini'],0),df_cnt.loc[i,'width'],df_cnt.loc[i,'fenzu']) #rect2 = plt.Rectangle((10,0),10,5)ax1.add_patch(rect) #ax1.add_patch(rect2) ax1.set_xlim(0, 100) ax1.set_ylim(0, 16) plt.show()
  • bar-柱狀圖
    兩種繪制方法:
    • 使用plt.bar()繪制
    • 使用Rectangle矩形類繪制柱狀圖
    • 使用plt.bar()繪制
      非常簡便。

    matplotlib.pyplot.bar(left, height, alpha=1, width=0.8, color=, edgecolor=, label=, lw=3)

    常用的參數:

    • left:x軸的位置序列,一般采用range函數產生一個序列,但是有時候可以是字符串
    • height:y軸的數值序列,也就是柱形圖的高度,一般就是我們需要展示的數據;
    • alpha:透明度,值越小越透明
    • width:為柱形圖的寬度,一般這是為0.8即可;
    • color或facecolor:柱形圖填充的顏色;
    • edgecolor:圖形邊緣顏色
    • label:解釋每個圖像代表的含義,這個參數是為legend()函數做鋪墊的,表示該次bar的標簽
    import matplotlib.pyplot as plt y = range(1,17) plt.bar(np.arange(16), y, alpha=0.5, width=0.5, color='yellow', edgecolor='red', label='The First Bar', lw=3)
    • 使用Rectangle矩形類繪制柱狀圖
      個人感覺比較麻煩。
    #import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111)"""class matplotlib.patches.Rectangle(xy, width, height, angle=0.0, **kwargs)x y:分別為矩形左下角的坐標 """ for i in range(1,17):rect = plt.Rectangle((i+0.25,0),0.5,i)ax1.add_patch(rect) ax1.set_xlim(0, 16) ax1.set_ylim(0, 16) plt.show() #import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111)"""class matplotlib.patches.Rectangle(xy, width, height, angle=0.0, **kwargs)x y:分別為矩形左下角的坐標 """ for i in range(1,17):rect = plt.Rectangle((i-1,0),0.5,i,angle=45)ax1.add_patch(rect) ax1.set_xlim(0, 16) ax1.set_ylim(0, 16) plt.show()

    3.2.3 繪制Polygon-多邊形

    matplotlib.patches.Polygon類是多邊形類。其基類是matplotlib.patches.Patch。

    構造函數:

    class matplotlib.patches.Polygon(xy, closed=True, **kwargs)

    參數說明:

    • xy:是一個N×2的numpy array,為多邊形的頂點。
    • closed:為True則指定多邊形將起點和終點重合從而顯式關閉多邊形

    在使用中,我們直接通過matplotlib.pyplot.fill()來繪制多邊形:

    import matplotlib.pyplot as plt x = np.linspace(0, 5 * np.pi, 1000) y1 = np.sin(x) y2 = np.sin(2 * x) plt.fill(x, y1, color = "g", alpha = 0.3)

    再用一個例子來說明plt.fill能用于繪制多邊形:

    import numpy as np import matplotlib.pyplot as pltdef koch_snowflake(order, scale=10):"""Return two lists x, y of point coordinates of the Koch snowflake.Arguments---------order : intThe recursion depth.scale : floatThe extent of the snowflake (edge length of the base triangle)."""def _koch_snowflake_complex(order):if order == 0:# initial triangleangles = np.array([0, 120, 240]) + 90return scale / np.sqrt(3) * np.exp(np.deg2rad(angles) * 1j)else:ZR = 0.5 - 0.5j * np.sqrt(3) / 3p1 = _koch_snowflake_complex(order - 1) # start pointsp2 = np.roll(p1, shift=-1) # end pointsdp = p2 - p1 # connection vectorsnew_points = np.empty(len(p1) * 4, dtype=np.complex128)new_points[::4] = p1new_points[1::4] = p1 + dp / 3new_points[2::4] = p1 + dp * ZRnew_points[3::4] = p1 + dp / 3 * 2return new_pointspoints = _koch_snowflake_complex(order)x, y = points.real, points.imag # 返回實部和虛部return x, y x, y = koch_snowflake(order=5)plt.figure(figsize=(8, 8)) plt.axis('equal') # 把單位長度都變的一樣。這樣做的好處就是對于圓來說更像圓 plt.fill(x, y) plt.show()

    3.2.3 繪制Wedge-契形

    matplotlib.patches.Polygon類是多邊形類。其基類是matplotlib.patches.Patch。

    在使用中,我們直接通過matplotlib.pyplot.pie()來繪制契形:

    matplotlib.pyplot.pie(x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=0, radius=1, counterclock=True, wedgeprops=None, textprops=None, center=0, 0, frame=False, rotatelabels=False, *, normalize=None, data=None)

    常用參數:

    • x:契型的形狀,一維數組。
    • explode:如果不是等于None,則是一個len(x)數組,它指定用于偏移每個楔形塊的半徑的分數。
    • labels:用于指定每個契型塊的標記,取值是列表或為None。
    • colors:餅圖循環使用的顏色序列。如果取值為>- None,將使用當前活動循環中的顏色。
    • startangle:餅狀圖開始的繪制的角度。
    • 使用plt.pie()繪制餅狀圖
    import matplotlib.pyplot as plt labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' x = [15, 30, 45, 10] explode = (0, 0.1, 0, 0) plt.pie(x, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show()
    • figure→axes→axis結構繪制餅狀圖
    import matplotlib.pyplot as plt labels = 'Frogs', 'Hogs', 'Dogs', 'Logs' x = [15, 30, 45, 10] explode = (0, 0.5, 0, 0) fig1, ax1 = plt.subplots() ax1.pie(x, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90) ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle. plt.show()
    • wedge繪制餅圖
    import matplotlib.pyplot as plt from matplotlib.patches import Circle, Wedge from matplotlib.collections import PatchCollectionfig = plt.figure() ax1 = fig.add_subplot(111) theta1 = 0 sizes = [15, 30, 45, 10] patches = [] patches += [Wedge((0.3, 0.3), .2, 0, 54), # Full circleWedge((0.3, 0.3), .2, 54, 162), # Full ringWedge((0.3, 0.3), .2, 162, 324), # Full sectorWedge((0.3, 0.3), .2, 324, 360), # Ring sector ] colors = 100 * np.random.rand(len(patches)) p = PatchCollection(patches, alpha=0.4) p.set_array(colors) ax1.add_collection(p) plt.show()

    3.3 collections-繪制一組對象的集合

    collections類是用來繪制一組對象的集合,collections有許多不同的子類,如RegularPolyCollection, CircleCollection, Pathcollection, 分別對應不同的集合子類型。其中比較常用的就是散點圖,它是屬于PathCollection子類,scatter方法提供了該類的封裝,根據x與y繪制不同大小或顏色標記的散點圖。

    3.3.1 scatter繪制散點圖

    最主要的參數:

    • x:數據點x軸的位置
    • y:數據點y軸的位置
    • s:尺寸大小
    • c:可以是單個顏色格式的字符串,也可以是一系列顏色
    • marker: 標記的類型

    其中marker是點的樣式,如圓形、矩形,甚至是字母之類的,詳情請看官網🔗matplotlib.markers

    • 使用Axes.scatter()繪制
    import matplotlib.pyplot as plt import numpy as np# Fixing random state for reproducibility np.random.seed(19680801)# unit area ellipse rx, ry = 3., 1. area = rx * ry * np.pi theta = np.arange(0, 2 * np.pi + 0.01, 0.1) verts = np.column_stack([rx / area * np.cos(theta), ry / area * np.sin(theta)])x, y, s, c = np.random.rand(4, 30) s *= 10**2.fig, ax = plt.subplots() ax.scatter(x, y, s, c, marker=verts)plt.show()
    • 使用plt.scatter()繪制
    x = [0,2,4,6,8,10] y = [10]*len(x) s = [20*2**n for n in range(len(x))] plt.scatter(x,y,s=s) plt.show() import numpy as np import matplotlib.pyplot as plt# Fixing random state for reproducibility np.random.seed(19680801)N = 50 x = np.random.rand(N) y = np.random.rand(N) colors = np.random.rand(N) area = (30 * np.random.rand(N))**2 # 0 to 15 point radiiplt.scatter(x, y, s=area, c=colors, alpha=0.5) plt.show()

    3.4 images

    images是matplotlib中繪制image圖像的類,其中最常用的imshow可以根據數組繪制成圖像。

    matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, *, data=None, **kwargs)

    使用imshow畫圖時首先需要傳入一個數組,數組對應的是空間內的像素位置和像素點的值,其中參數interpolation參數可以設置不同的差值方法,具體效果如下:

    import matplotlib.pyplot as plt import numpy as np methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16','spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric','catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']grid = np.random.rand(4, 4) # 4×4大小的圖片fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),subplot_kw={'xticks': [], 'yticks': []})for ax, interp_method in zip(axs.flat, methods):ax.imshow(grid, interpolation=interp_method, cmap='afmhot')ax.set_title(str(interp_method))plt.tight_layout() plt.show()

    interpolation='antialiased'時,有抗鋸齒效果:

    import matplotlib.pyplot as plt import numpy as np methods = [None, 'none', 'nearest', 'bilinear', 'bicubic', 'spline16','spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric','catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos']grid = np.random.rand(4, 4)fig, axs = plt.subplots(nrows=3, ncols=6, figsize=(9, 6),subplot_kw={'xticks': [], 'yticks': []})for ax, interp_method in zip(axs.flat, methods):"""interpolation = 'none' works well when a big image is scaled down, while interpolation = 'nearest' works well when a small image is scaled up.default: 'antialiased'"""ax.imshow(grid, interpolation='antialiased', cmap='afmhot') # cmap: colormap,圖像的顏色樣式ax.set_title(str(interp_method))plt.tight_layout() # 輸出的圖像看起來更舒服 plt.show()

    參數cmap代表著不同的顏色,舉些例子:

    將上文的代碼的cmap='afmhot'修改為cmap='plasma',圖像顏色改變:

    4 對象容器 - Object container

    容器會包含一些primitives,并且容器還有它自身的屬性。

    4.1 Figure容器

    注意Figure默認的坐標系是以像素為單位,你可能需要轉換成figure坐標系:(0,0)表示左下點,(1,1)表示右上點。

    Figure容器的常見屬性:

    • Figure.patch屬性:Figure的背景矩形
    • Figure.axes屬性:一個Axes實例的列表(包括Subplot)
    • Figure.images屬性:一個FigureImages patch列表
    • Figure.lines屬性:一個Line2D實例的列表(很少使用)
    • Figure.legends屬性:一個Figure Legend實例列表(不同于Axes.legends)
    • Figure.texts屬性:一個Figure Text實例列表
      當我們向圖表添加Figure.add_subplot()或者Figure.add_axes()元素時,這些都會被添加到Figure.axes列表中。
    import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(211) # 作一幅2*1的圖,選擇第1個子圖 ax2 = fig.add_axes([0.1, 0.1, 0.5, 0.3]) # 位置參數,四個數分別代表了(left,bottom,width,height) #print(ax1) #包含了subplot和axes兩個實例, 剛剛添加的 print(fig.axes) # fig.axes 中包含了subplot和axes兩個實例, 剛剛添加的 import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(211) # 作一幅2*1的圖,選擇第1個子圖 ax2 = fig.add_axes([0.1, 0.1, 0.5, 0.3]) # 位置參數,四個數分別代表了(left,bottom,width,height) print(ax1) #包含了subplot和axes兩個實例, 剛剛添加的 #print(fig.axes) # fig.axes 中包含了subplot和axes兩個實例, 剛剛添加的

    既然Figure.axes里面存有subplot和axes,那我們遍歷看看:

    import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(211) # Add an Axes to the figure as part of a subplot arrangement. ax2 = fig.add_axes([1,1,0.2,0.2]) ax3 = fig.add_subplot(212)for ax in fig.axes:ax.grid(True)

    4.2 Axes容器

    matplotlib.axes.Axes是matplotlib的核心。大量的用于繪圖的Artist存放在它內部,并且它有許多輔助方法來創建和添加Artist給它自己。

    Axes有許多方法用于繪圖,如.plot()、.text()、.hist()、.imshow()等方法用于創建大多數常見的primitive(如Line2D,Rectangle,Text,Image等等)

    和Figure容器類似,Axes包含了一個patch屬性:

    import numpy as np import matplotlib.pyplot as plt import matplotlibfig = plt.figure() ax = fig.add_subplot(111) ## Add an Axes to the figure as part of a subplot rect = ax.patch # axes的patch是一個Rectangle實例 rect.set_facecolor('blue')

    不應該直接通過Axes.lines和Axes.patches列表來添加圖表,還記得嗎?Axes是從Artist來的,所以可以用add_*,使用Axes的輔助方法.add_line()和.add_patch()方法來直接添加。

    4.2.1 Subplot和Axes的區別

    Subplot就是一個特殊的Axes,其實例是位于網格中某個區域的Subplot實例,Figure.add_subplot(),通過Figure.add_axes([left,bottom,width,height])可以創建一個任意區域的Axes。

    4.3 Axis容器

    每個Axis都有一個label屬性,也有主刻度列表和次刻度列表。這些ticks是axis.XTick和axis.YTick實例,它們包含著line primitive以及text primitive用來渲染刻度線以及刻度文本。

    刻度是動態創建的,只有在需要創建的時候才創建(比如縮放的時候)。Axis也提供了一些輔助方法來獲取刻度文本、刻度線位置等等:
    常見的如下:

    # 不用print,直接顯示結果 from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all"fig, ax = plt.subplots() x = range(0,5) y = [2,5,7,8,10] plt.plot(x, y, '-')axis = ax.xaxis # axis為X軸對象 axis.get_ticklocs() # 獲取刻度線位置 axis.get_ticklabels() # 獲取刻度label列表(一個Text實例的列表)。 可以通過minor=True|False關鍵字參數控制輸出minor還是major的tick label。 axis.get_ticklines() # 獲取刻度線列表(一個Line2D實例的列表)。 可以通過minor=True|False關鍵字參數控制輸出minor還是major的tick line。 axis.get_data_interval()# 獲取軸刻度間隔 axis.get_view_interval()# 獲取軸視角(位置)的間隔

    下面的例子展示了如何調整一些軸和刻度的屬性(忽略美觀度,僅作調整參考):

    fig = plt.figure() # 創建一個新圖表 rect = fig.patch # 矩形實例并將其設為黃色 rect.set_facecolor('lightgoldenrodyellow')ax1 = fig.add_axes([0.1, 0.3, 0.4, 0.4]) # 創一個axes對象,從(0.1,0.3)的位置開始,寬和高都為0.4, rect = ax1.patch # ax1的矩形設為灰色 rect.set_facecolor('lightslategray')for label in ax1.xaxis.get_ticklabels(): # 調用x軸刻度標簽實例,是一個text實例label.set_color('red') # 顏色label.set_rotation(45) # 旋轉角度label.set_fontsize(16) # 字體大小for line in ax1.yaxis.get_ticklines():# 調用y軸刻度線條實例, 是一個Line2D實例line.set_color('green') # 顏色line.set_markersize(25) # marker大小line.set_markeredgewidth(2)# marker粗細plt.show()

    4.4 Tick容器

    matplotlib.axis.Tick是從Figure到Axes到Axis到Tick中最末端的容器對象。

    y軸分為左右兩個,因此tick1對應左側的軸;tick2對應右側的軸。
    x軸分為上下兩個,因此tick1對應下側的軸;tick2對應上側的軸。

    下面的例子展示了,如何將Y軸右邊軸設為主軸,并將標簽設置為美元符號且為綠色:

    import numpy as np import matplotlib.pyplot as plt import matplotlibfig, ax = plt.subplots() ax.plot(100*np.random.rand(20))# 設置ticker的顯示格式 formatter = matplotlib.ticker.FormatStrFormatter('$%3.2f') # 3.3f:整數部分隨便填(?不太清楚),小數保留2位 ax.yaxis.set_major_formatter(formatter)# 設置ticker的參數,右側為主軸,顏色為綠色 # which=['major','minor','both'] ax.yaxis.set_tick_params(which='major',labelcolor='green',labelleft=False,labelright=True)plt.show()

    作業

    思考題

  • primitives 和 container的區別和聯系是什么?
    primitives是各種基本元素,而container是裝基本元素的容器。相同點在于它們都是Artist的子類,都可以通過add_*和set_*來添加和設置屬性。
  • 四個容器的聯系和區別是么?他們分別控制一張圖表的哪些要素?
    figure axes axis tick是”由大到小“的,就跟畫畫一樣,figure是畫布,axes是畫筆,axis就是畫的正方形輪廓,tick就是上面的刻度。如圖所示:
  • 繪圖題

  • 教程中展示的案例都是單一圖,請自行創建數據,畫出包含6個子圖的線圖,要求:
    子圖排布是 2 * 3 (2行 3列);
    線圖可用教程中line2D方法繪制;
    需要設置每個子圖的橫坐標和縱坐標刻度;
    并設置整個圖的標題,橫坐標名稱,以及縱坐標名稱
  • import matplotlib.pyplot as plot from matplotlib.lines import Line2D import matplotlib.ticker as ticker import numpy as npfig,axs = plt.subplots(2,3,figsize=(10,5))def f(x,i):function = [np.sin(x),np.log(x),np.cos(x),5*x**2+3,1/x,x**3]return function[i]for i in range(6):print(i)row_index = i // 3col_index = i % 3x = np.random.randint(1,10,10)y = f(x,i)color = np.random.rand(3) # R G B 圖片#line = Line2D(x,y)#line.set_color(color)axs[row_index,col_index].plot(x,y,color=color)#axs[row_index,col_index].add_line(line)axs[row_index,col_index].set_ylabel("test_y:"+str(i))axs[row_index,col_index].set_xlabel("test_x:"+str(i))axs[row_index,col_index].xaxis.set_major_locator(ticker.AutoLocator())axs[row_index,col_index].yaxis.set_major_locator(ticker.AutoLocator())fig.suptitle("This is my homework!") fig.text(0,0.5,'y_axis',horizontalalignment='left') fig.text(0.5,0,'x_axis',verticalalignment='center') plt.tight_layout()
  • 分別用一組長方形柱和填充面積的方式模仿畫出下圖,函數 y = -1 * (x - 2) * (x - 8) +10 在區間[2,9]的積分面積
  • import matplotlib.pyplot as plt import numpy as npdef f(x):y = -1 * (x - 2) * (x - 8) +10return y fig, axs = plt.subplots(2,1,figsize=(6,8))for i in np.arange(2,9,0.2):rect = plt.Rectangle((i,0),0.1,f(i),color='lightgray')axs[0].add_patch(rect)x = np.arange(0,11,0.1) y = f(x)axs[0].plot(x,y,'r') axs[0].set_ylim(0,20)axs[1].plot(x,y,'r') axs[1].fill_between(x,y,where=(x>=2)&(x<=9),facecolor='lightgray') axs[1].set_ylim(0,20) 與50位技術專家面對面20年技術見證,附贈技術全景圖

    總結

    以上是生活随笔為你收集整理的数据可视化组队学习:《Task02 - 艺术画笔见乾坤》笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。