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

歡迎訪問 生活随笔!

生活随笔

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

编程问答

数据可视化组队学习:《Task04 - 文字图例尽眉目》笔记

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

文章目錄

  • 前言
  • 1 Figure和Axes的文本
    • 1.1 text
    • 1.2 title和set_title
    • 1.3 figtext和text
    • 1.4 suptitle
    • 1.5 xlabel和ylabel
    • 1.6 annotate
    • 1.7 字體的設置方法
    • 總結:1.1~1.7知識點匯總
    • 1.8 數學表達式
  • 2 tick上的text
    • 2.1 Tick Locators and Formatters
      • 2.1.1 Formatters
      • 2.1.2 Locator
      • 2.1.3 調整x、y軸的位置
  • 3 Legend
  • 作業

前言

本博客是Task04的筆記。


1 Figure和Axes的文本

1.1 text


說明:

參數:此方法接受以下描述的參數:
s:此參數是要添加的文本。
xy:此參數是放置文本的點(x,y)。
fontdict:此參數是一個可選參數,并且是一個覆蓋默認文本屬性的字典。如果fontdict為None,則由rcParams確定默認值。
返回值:此方法返回作為創建的文本實例的文本。

#fontdict學習的案例 #學習的過程中請嘗試更換不同的fontdict字典的內容,以便于更好的掌握 import numpy as np import matplotlib.pyplot as plt #---------設置字體樣式,分別是字體,顏色,寬度,大小 font1 = {'family': 'Times New Roman','color': 'purple','weight': 'normal','size': 16,} font2 = {'family': 'Times New Roman','color': 'red','weight': 'normal','size': 16,} font3 = {'family': 'serif','color': 'blue','weight': 'bold','size': 14,} font4 = {'family': 'Calibri','color': 'navy','weight': 'normal','size': 17,} #-----------四種不同字體顯示風格-----#-------建立函數---------- x = np.linspace(0.0, 5.0, 100) y = np.cos(2*np.pi*x) * np.exp(-x/3) #-------繪制圖像,添加標注---------- plt.plot(x, y, '--') plt.title('Damped exponential decay', fontdict=font1) #------添加文本在指定的坐標處------------ plt.text(2, 0.65, r'$\cos(2 \pi x) \exp(-x/3)$', fontdict=font2) #---------設置坐標標簽 plt.xlabel('Y=time (s)', fontdict=font3) plt.ylabel('X=voltage(mv)', fontdict=font4)# 調整圖像邊距 plt.subplots_adjust(left=0.15) plt.show()

給test加個框框:

import matplotlib.pyplot as pltplt.text(0.6, 0.7, "I ?", size=50, rotation=30.,ha="center", va="center",bbox=dict(boxstyle="round", # bbox:以框框形式輸出,要帶上參數ec=(1., 0.5, 0.5), # edgecolorfc=(1., 0.8, 0.8), # facecoloor))plt.text(0.8, 0.7, "Datawhale", size=40, rotation=-25.,ha="right", va="top",bbox=dict(boxstyle="square", # bbox:以框框形式輸出,要帶上參數ec=(1., 0.5, 0.5), # edgecolorfc=(1., 0.8, 0.8), # facecoloor))plt.show()

1.2 title和set_title

pyplot API:matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
OO API:Axes.set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)

import matplotlib.pyplot as pltlabels = ['G1', 'G2', 'G3', 'G4', 'G5'] men_means = [20, 35, 30, 35, 27] women_means = [25, 32, 34, 20, 25] men_std = [2, 3, 4, 1, 2] women_std = [3, 5, 2, 3, 3] width = 0.35 # the width of the bars: can also be len(x) sequencefig, ax = plt.subplots()ax.bar(labels, men_means, width, yerr=men_std, label='Men') ax.bar(labels, women_means, width, yerr=women_std, bottom=men_means,label='Women')ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.legend()plt.show()

1.3 figtext和text

pyplot API:matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs)
OO API:text(self, x, y, s, fontdict=None,**kwargs)

1.4 suptitle

調用方式如下:

fig.suptitle('This is the figure title', fontsize=12) plt.suptitle("GridSpec Inside GridSpec")

1.5 xlabel和ylabel

pyplot API
matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, , loc=None, **kwargs)
matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None,, loc=None, **kwargs)
OO API:
Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, , loc=None, **kwargs)
Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None,, loc=None, **kwargs)

兩種調用方式:

import numpy as np import matplotlib.pyplot as pltfont = {'family': 'serif','color': 'darkred','weight': 'normal','size': 16,}x = np.linspace(0.0, 5.0, 100) y = np.cos(2*np.pi*x) * np.exp(-x)plt.plot(x, y, 'k') plt.title('Damped exponential decay', fontdict=font) plt.text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', fontdict=font) plt.xlabel('time (s)', fontdict=font) plt.ylabel('voltage (mV)', fontdict=font)# Tweak spacing to prevent clipping of ylabel plt.subplots_adjust(left=0.15) plt.show()

#文本屬性的輸入一種是通過**kwargs屬性這種方式,一種是通過操作 matplotlib.font_manager.FontProperties 方法 #該鏈接是FontProperties方法的介紹 https://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontProperties from matplotlib.font_manager import FontProperties import matplotlib.pyplot as plt import numpy as npx1 = np.linspace(0.0, 5.0, 100) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)font = FontProperties() font.set_family('serif') font.set_name('Times New Roman') font.set_style('italic')fig, ax = plt.subplots(figsize=(5, 3)) fig.subplots_adjust(bottom=0.15, left=0.2) ax.plot(x1, y1) ax.set_xlabel('time [s]', fontsize='large', fontweight='bold') ax.set_ylabel('Damped oscillation [V]', fontproperties=font)plt.show()

1.6 annotate

pyplot API:matplotlib.pyplot.annotate(text, xy, *args,**kwargs)
OO API:Axes.annotate(self, text, xy, *args,**kwargs)

參數
text:str,該參數是指注釋文本的內容
xy:該參數接受二維元組(float, float),是指要注釋的點。其二維元組所在的坐標系由xycoords參數決定
xytext:注釋文本的坐標點,也是二維元組,默認與xy相同

import numpy as np import matplotlib.pyplot as pltfig, ax = plt.subplots()t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = ax.plot(t, s, lw=2)ax.annotate('local max', xy=(2, 1), xytext=(3, 1.5),arrowprops=dict(facecolor='black', shrink=0.05),) ax.set_ylim(-2, 2) plt.show()

import matplotlib.pyplot as plt def demo_con_style(ax, connectionstyle):x1, y1 = 0.3, 0.2x2, y2 = 0.8, 0.6ax.plot([x1, x2], [y1, y2], ".")ax.annotate("",xy=(x1, y1), xycoords='data',xytext=(x2, y2), textcoords='data',arrowprops=dict(arrowstyle="->", color="0.5",shrinkA=5, shrinkB=5,patchA=None, patchB=None,connectionstyle=connectionstyle,),)ax.text(.05, .95, connectionstyle.replace(",", ",\n"),transform=ax.transAxes, ha="left", va="top")fig, axs = plt.subplots(3, 5, figsize=(8, 4.8)) demo_con_style(axs[0, 0], "angle3,angleA=90,angleB=0") demo_con_style(axs[1, 0], "angle3,angleA=0,angleB=90") demo_con_style(axs[0, 1], "arc3,rad=0.") demo_con_style(axs[1, 1], "arc3,rad=0.3") demo_con_style(axs[2, 1], "arc3,rad=-0.3") demo_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0") demo_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5") demo_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5") demo_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0") demo_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5") demo_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0") demo_con_style(axs[0, 4], "bar,fraction=0.3") demo_con_style(axs[1, 4], "bar,fraction=-0.3") demo_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")for ax in axs.flat:ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1) fig.tight_layout(pad=0.2)plt.show()

#以下兩個block懂了之后,annotate基本懂了 #如果想更深入學習可以參看官網案例學習https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.annotate.html#matplotlib.axes.Axes.annotate import numpy as np import matplotlib.pyplot as plt# 以步長0.005繪制一個曲線 x = np.arange(0, 10, 0.005) y = np.exp(-x/2.) * np.sin(2*np.pi*x)fig, ax = plt.subplots() ax.plot(x, y) ax.set_xlim(0, 10)#設置x軸的范圍 ax.set_ylim(-1, 1)#設置x軸的范圍# 被注釋點的數據軸坐標和所在的像素 xdata, ydata = 5, 0 xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))# 設置注釋文本的樣式和箭頭的樣式 bbox = dict(boxstyle="round", fc="0.8") arrowprops = dict(arrowstyle = "->",connectionstyle = "angle,angleA=0,angleB=90,rad=10")# 設置偏移量 offset = 72 # xycoords默認為'data'數據軸坐標,對坐標點(5,0)添加注釋 # 注釋文本參考被注釋點設置偏移量,向左2*72points,向上72points ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata),(xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',bbox=bbox, arrowprops=arrowprops)# xycoords以繪圖區左下角為參考,單位為像素 # 注釋文本參考被注釋點設置偏移量,向右0.5*72points,向下72points disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay),(xdisplay, ydisplay), xytext=(0.5*offset, -offset),xycoords='figure pixels',textcoords='offset points',bbox=bbox, arrowprops=arrowprops) plt.show()


關于參數xycoords:

ValueDescription
‘figure points’Points from the lower left of the figure
‘figure pixels’Pixels from the lower left of the figure
import numpy as np import matplotlib.pyplot as plt# 繪制一個極地坐標,再以0.001為步長,畫一條螺旋曲線 fig = plt.figure() ax = fig.add_subplot(111, polar=True) r = np.arange(0,1,0.001) theta = 2 * 2*np.pi * r line, = ax.plot(theta, r, color='#ee8d18', lw=3)# 對索引為800處畫一個圓點,并做注釋 ind = 800 thisr, thistheta = r[ind], theta[ind] ax.plot([thistheta], [thisr], 'o') ax.annotate('a polar annotation',xy=(thistheta, thisr), # 被注釋點遵循極坐標系,坐標為角度和半徑xytext=(0.05, 0.05), # 注釋文本放在繪圖區的0.05百分比處textcoords='figure fraction',arrowprops=dict(facecolor='black', shrink=0.05),# 箭頭線為黑色,兩端縮進5%horizontalalignment='left',# 注釋文本的左端和低端對齊到指定位置verticalalignment='bottom',) plt.show()

1.7 字體的設置方法

  • 全局字體設置
#該block講述如何在matplotlib里面,修改字體默認屬性,完成全局字體的更改。 import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimSun'] # 指定默認字體為新宋體。 plt.rcParams['axes.unicode_minus'] = False # 解決保存圖像時 負號'-' 顯示為方塊和報錯的問題。
  • 局部字體設置
#局部字體的修改方法1 import matplotlib.pyplot as plt import matplotlib.font_manager as fontmgx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] plt.plot(x, label='小示例圖標簽')# 直接用字體的名字。 plt.xlabel('x 軸名稱參數', fontproperties='Microsoft YaHei', fontsize=16) # 設置x軸名稱,采用微軟雅黑字體 plt.ylabel('y 軸名稱參數', fontproperties='Microsoft YaHei', fontsize=14) # 設置Y軸名稱 plt.title('坐標系的標題', fontproperties='Microsoft YaHei', fontsize=20) # 設置坐標系標題的字體 plt.legend(loc='lower right', prop={"family": 'Microsoft YaHei'}, fontsize=10) # 小示例圖的字體設置

總結:1.1~1.7知識點匯總

#這是以上學習內容的總結案例 import matplotlib import matplotlib.pyplot as pltfig = plt.figure() ax = fig.add_subplot(111) fig.subplots_adjust(top=0.85)# Set titles for the figure and the subplot respectively fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold') ax.set_title('axes title')ax.set_xlabel('xlabel') ax.set_ylabel('ylabel')# Set both x- and y-axis limits to [0, 10] instead of default [0, 1] ax.axis([0, 10, 0, 10])ax.text(3, 8, 'boxed italics text in data coords', style='italic',bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15) font1 = {'family': 'Times New Roman','color': 'purple','weight': 'normal','size': 10,} ax.text(3, 2, 'unicode: Institut für Festk?rperphysik',fontdict=font1) ax.text(0.95, 0.01, 'colored text in axes coords',verticalalignment='bottom', horizontalalignment='right', #右下角的坐標在圖的0.95倍x軸長度、0.01倍y軸長度處transform=ax.transAxes,color='green', fontsize=15)ax.plot([2], [1], 'o') ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),arrowprops=dict(facecolor='black', shrink=0.05))plt.show()

1.8 數學表達式

使用latex語法即可。

2 tick上的text

#一般繪圖時會自動創建刻度,而如果通過上面的例子使用set_ticks創建刻度可能會導致tick的范圍與所繪制圖形的范圍不一致的問題。 #所以在下面的案例中,axs[1]中set_xtick的設置要與數據范圍所對應,然后再通過set_xticklabels設置刻度所對應的標簽 import numpy as np import matplotlib.pyplot as plt fig, axs = plt.subplots(2, 1, figsize=(6, 4), tight_layout=True) x1 = np.linspace(0.0, 6.0, 100) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) axs[0].plot(x1, y1) axs[0].set_xticks([0,1,2,3,4,5,6])axs[1].plot(x1, y1) axs[1].set_xticks([0,1,2,3,4,5,6])#要將x軸的刻度放在數據范圍中的哪些位置 axs[1].set_xticklabels(['zero','one', 'two', 'three', 'four', 'five','six'],#設置刻度對應的標簽rotation=30, fontsize='small')#rotation選項設定x刻度標簽傾斜30度。 axs[1].xaxis.set_ticks_position('bottom')#set_ticks_position()方法是用來設置刻度所在的位置,常用的參數有bottom、top、both、none print(axs[1].xaxis.get_ticklines()) plt.show()

2.1 Tick Locators and Formatters

  • 設置標簽的位置

Axis.set_major_locator
Axis.set_minor_locator

  • 設置標簽的格式

Axis.set_major_formatter
Axis.set_minor_formatter

2.1.1 Formatters

  • 接收字符串
  • import matplotlib# 接收字符串格式的例子 x1 = np.linspace(0.0, 6.0, 100) y1 = np.cos(2 * np.pi * x1) * np.exp(-x1) fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True) for n, ax in enumerate(axs.flat):ax.plot(x1*10., y1)formatter = matplotlib.ticker.FormatStrFormatter('%1.1f') axs[0, 1].xaxis.set_major_formatter(formatter)formatter = matplotlib.ticker.FormatStrFormatter('-%1.1f') axs[1, 0].xaxis.set_major_formatter(formatter)formatter = matplotlib.ticker.FormatStrFormatter('%1.5f') axs[1, 1].xaxis.set_major_formatter(formatter)plt.show()


    2. 接收函數

    def formatoddticks(x, pos):"""Format odd tick positions."""if x % 2:return f'{x:1.2f}'else:return ''fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True) ax.plot(x1, y1) ax.xaxis.set_major_formatter(formatoddticks) plt.show()

    2.1.2 Locator

    使用plt或者matplotlib.ticker獲得各種locator,然后通過axs.xaxis.set_major_locator(locator)繪制:

    • locator=plt.MaxNLocator(nbins=7)
    • llocator=plt.FixedLocator(locs=[0,0.5,1.5,2.5,3.5,4.5,5.5,6])#直接指定刻度所在的位置
    • llocator=plt.AutoLocator()#自動分配刻度值的位置
    • llocator=plt.IndexLocator(offset=0.5, base=1)#面元間距是1,從0.5開始
    • llocator=plt.MultipleLocator(1.5)#將刻度的標簽設置為1.5的倍數
    • llocator=plt.LinearLocator(numticks=5)#線性劃分5等分,4個刻度
    # 接收各種locator的例子 fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True) for n, ax in enumerate(axs.flat):ax.plot(x1*10., y1)locator = matplotlib.ticker.AutoLocator() axs[0, 0].xaxis.set_major_locator(locator)locator = matplotlib.ticker.MaxNLocator(nbins=10) axs[0, 1].xaxis.set_major_locator(locator)locator = matplotlib.ticker.MultipleLocator(5) axs[1, 0].xaxis.set_major_locator(locator)locator = matplotlib.ticker.FixedLocator([0,7,14,21,28]) axs[1, 1].xaxis.set_major_locator(locator)plt.show()

    2.1.3 調整x、y軸的位置

    #這個案例中展示了如何進行坐標軸的移動,如何更改刻度值的樣式 import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3,3,50) y1 = 2*x+1 y2 = x**2 plt.figure() plt.plot(x,y2) plt.plot(x,y1,color='red',linewidth=1.0,linestyle = '--') plt.xlim((-3,5)) plt.ylim((-3,5)) plt.xlabel('x') plt.ylabel('y') new_ticks1 = np.linspace(-3,5,5) plt.xticks(new_ticks1) plt.yticks([-2,0,2,5],[r'$one\ shu$',r'$\alpha$',r'$three$',r'four']) ''' 上一行代碼是將y軸上的小標改成文字,其中,空格需要增加\,即'\ ',$可將格式更改成數字模式,如果需要輸入數學形式的α,則需要用\轉換,即\alpha 如果使用面向對象的命令進行畫圖,那么下面兩行代碼可以實現與 plt.yticks([-2,0,2,5],[r'$one\ shu$',r'$\alpha$',r'$three$',r'four']) 同樣的功能 axs.set_yticks([-2,0,2,5]) axs.set_yticklabels([r'$one\ shu$',r'$\alpha$',r'$three$',r'four']) ''' ax = plt.gca()#gca = 'get current axes' 獲取現在的軸 ''' ax = plt.gca()是獲取當前的axes,其中gca代表的是get current axes。 fig=plt.gcf是獲取當前的figure,其中gcf代表的是get current figure。許多函數都是對當前的Figure或Axes對象進行處理, 例如plt.plot()實際上會通過plt.gca()獲得當前的Axes對象ax,然后再調用ax.plot()方法實現真正的繪圖。而在本例中則可以通過ax.spines方法獲得當前頂部和右邊的軸并將其顏色設置為不可見 然后將左邊軸和底部的軸所在的位置重新設置 最后再通過set_ticks_position方法設置ticks在x軸或y軸的位置,本示例中因所設置的bottom和left是ticks在x軸或y軸的默認值,所以這兩行的代碼也可以不寫 ''' ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['left'].set_position(('data',0)) # data 0:將底部設置在數據的y=0處 ax.spines['bottom'].set_position(('data',0))# data 0:將左部設置在數據的x=0處 ax.xaxis.set_ticks_position('bottom') #設置ticks在x軸的位置 ax.yaxis.set_ticks_position('left') #設置ticks在y軸的位置 plt.show()

    3 Legend

    常用的幾個參數:

    (1)設置圖列位置

    plt.legend(loc=‘upper center’) 等同于plt.legend(loc=9)

    0: ‘best’
    1: ‘upper right’
    2: ‘upper left’
    3: ‘lower left’ |
    4: ‘lower right’
    5: ‘right’
    6: ‘center left’ |
    7: ‘center right’
    8: ‘lower center’
    9: ‘upper center’
    10: ‘center’ |

    (2)設置圖例字體大小

    fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}

    (3)設置圖例邊框及背景

    plt.legend(loc=‘best’,frameon=False) #去掉圖例邊框
    plt.legend(loc=‘best’,edgecolor=‘blue’) #設置圖例邊框顏色
    plt.legend(loc=‘best’,facecolor=‘blue’) #設置圖例背景顏色,若無邊框,參數無效

    (4)設置圖例標題

    legend = plt.legend([“CH”, “US”], title=‘China VS Us’)

    (5)設置圖例名字及對應關系

    legend = plt.legend([p1, p2], [“CH”, “US”])

    line_up, = plt.plot([1, 2, 3], label='Line 2') line_down, = plt.plot([3, 2, 1], label='Line 1') plt.legend([line_up, line_down], ['Line Up', 'Line Down'],loc=5, title='line',frameon=False)#loc參數設置圖例所在的位置,title設置圖例的標題,frameon參數將圖例邊框給去掉

    添加多個lengend,plt.gca().add_artist():

    #這個案例是顯示多圖例legend import matplotlib.pyplot as plt import numpy as np x = np.random.uniform(-1, 1, 4) y = np.random.uniform(-1, 1, 4) p1, = plt.plot([1,2,3]) p2, = plt.plot([3,2,1]) l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')p3 = plt.scatter(x[0:2], y[0:2], marker = 'D', color='r') p4 = plt.scatter(x[2:], y[2:], marker = 'D', color='g') # 下面這行代碼由于添加了新的legend,所以會將l1從legend中給移除 plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1) # 為了保留之前的l1這個legend,所以必須要通過plt.gca()獲得當前的axes,然后將l1作為單獨的artist plt.gca().add_artist(l1)

    作業

  • 嘗試在一張圖中運用所講過的功能,對title、text、xlable、ylabel、數學表達式、tick and ticklabel、legend進行詳細的設計.
  • # Dolphins圖來源:https://matplotlib.org/gallery/shapes_and_collections/dolphin.html#sphx-glr-gallery-shapes-and-collections-dolphin-pyimport matplotlib.cm as cm import matplotlib.pyplot as plt from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path from matplotlib.transforms import Affine2D import numpy as np# Fixing random state for reproducibility np.random.seed(19680801)r = np.random.rand(50) t = np.random.rand(50) * np.pi * 2.0 x = r * np.cos(t) y = r * np.sin(t)fig, ax = plt.subplots(figsize=(6, 6)) circle = Circle((0, 0), 1, facecolor='none',edgecolor=(0, 0.8, 0.8), linewidth=3, alpha=0.5) ax.add_patch(circle)im = plt.imshow(np.random.random((100, 100)),origin='lower', cmap=cm.winter,interpolation='spline36',extent=([-1, 1, -1, 1])) im.set_clip_path(circle)plt.plot(x, y, 'o', color=(0.9, 0.9, 1.0), alpha=0.8)# Dolphin from OpenClipart library by Andy Fitzsimon # <cc:License rdf:about="http://web.resource.org/cc/PublicDomain"> # <cc:permits rdf:resource="http://web.resource.org/cc/Reproduction"/> # <cc:permits rdf:resource="http://web.resource.org/cc/Distribution"/> # <cc:permits rdf:resource="http://web.resource.org/cc/DerivativeWorks"/> # </cc:License>dolphin = """ M -0.59739425,160.18173 C -0.62740401,160.18885 -0.57867129,160.11183 -0.57867129,160.11183 C -0.57867129,160.11183 -0.5438361,159.89315 -0.39514638,159.81496 C -0.24645668,159.73678 -0.18316813,159.71981 -0.18316813,159.71981 C -0.18316813,159.71981 -0.10322971,159.58124 -0.057804323,159.58725 C -0.029723983,159.58913 -0.061841603,159.60356 -0.071265813,159.62815 C -0.080250183,159.65325 -0.082918513,159.70554 -0.061841203,159.71248 C -0.040763903,159.7194 -0.0066711426,159.71091 0.077336307,159.73612 C 0.16879567,159.76377 0.28380306,159.86448 0.31516668,159.91533 C 0.3465303,159.96618 0.5011127,160.1771 0.5011127,160.1771 C 0.63668998,160.19238 0.67763022,160.31259 0.66556395,160.32668 C 0.65339985,160.34212 0.66350443,160.33642 0.64907098,160.33088 C 0.63463742,160.32533 0.61309688,160.297 0.5789627,160.29339 C 0.54348657,160.28968 0.52329693,160.27674 0.50728856,160.27737 C 0.49060916,160.27795 0.48965803,160.31565 0.46114204,160.33673 C 0.43329696,160.35786 0.4570711,160.39871 0.43309565,160.40685 C 0.4105108,160.41442 0.39416631,160.33027 0.3954995,160.2935 C 0.39683269,160.25672 0.43807996,160.21522 0.44567915,160.19734 C 0.45327833,160.17946 0.27946869,159.9424 -0.061852613,159.99845 C -0.083965233,160.0427 -0.26176109,160.06683 -0.26176109,160.06683 C -0.30127962,160.07028 -0.21167141,160.09731 -0.24649368,160.1011 C -0.32642366,160.11569 -0.34521187,160.06895 -0.40622293,160.0819 C -0.467234,160.09485 -0.56738444,160.17461 -0.59739425,160.18173 """vertices = [] codes = [] parts = dolphin.split() i = 0 code_map = {'M': Path.MOVETO,'C': Path.CURVE4,'L': Path.LINETO, }while i < len(parts):path_code = code_map[parts[i]]npoints = Path.NUM_VERTICES_FOR_CODE[path_code]codes.extend([path_code] * npoints)vertices.extend([[*map(float, y.split(','))]for y in parts[i + 1:][:npoints]])i += npoints + 1 vertices = np.array(vertices) vertices[:, 1] -= 160dolphin_path = Path(vertices, codes) dolphin_patch = PathPatch(dolphin_path, facecolor=(0.6, 0.6, 0.6),edgecolor=(0.0, 0.0, 0.0)) ax.add_patch(dolphin_patch)vertices = Affine2D().rotate_deg(60).transform(vertices) dolphin_path2 = Path(vertices, codes) dolphin_patch2 = PathPatch(dolphin_path2, facecolor=(0.5, 0.5, 0.5),edgecolor=(0.0, 0.0, 0.0)) ax.add_patch(dolphin_patch2)""" 下面是作業代碼 """ font = {'family': 'serif','color': 'blue','weight': 'bold','size': 14,} ax.set_title("Two Dolphins!",fontdict=font,loc='center') ax.text(-0.85,0.9,r'$1+1=2$',color='purple') ax.set_xlabel('x') ax.set_ylabel('y',rotation=0.5) ax.set_xticks([-1,-0.5,0,0.5,1]) ax.set_xticklabels(['I','?','Datawhale','!',"!"]) ax.plot(1,1,'blue') ax.annotate('a point',xy=(1,1),xytext=(-0.85,-0.85),arrowprops=dict(facecolor='red',width=0.5)) ax.legend('text',loc='lower right',fontsize='small')plt.show()

    總結

    以上是生活随笔為你收集整理的数据可视化组队学习:《Task04 - 文字图例尽眉目》笔记的全部內容,希望文章能夠幫你解決所遇到的問題。

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