数据可视化组队学习:《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 字體的設(shè)置方法
- 總結(jié):1.1~1.7知識(shí)點(diǎn)匯總
- 1.8 數(shù)學(xué)表達(dá)式
- 2 tick上的text
- 2.1 Tick Locators and Formatters
- 2.1.1 Formatters
- 2.1.2 Locator
- 2.1.3 調(diào)整x、y軸的位置
- 3 Legend
- 作業(yè)
前言
本博客是Task04的筆記。
1 Figure和Axes的文本
1.1 text
說明:
參數(shù):此方法接受以下描述的參數(shù):
s:此參數(shù)是要添加的文本。
xy:此參數(shù)是放置文本的點(diǎn)(x,y)。
fontdict:此參數(shù)是一個(gè)可選參數(shù),并且是一個(gè)覆蓋默認(rèn)文本屬性的字典。如果fontdict為None,則由rcParams確定默認(rèn)值。
返回值:此方法返回作為創(chuàng)建的文本實(shí)例的文本。
給test加個(gè)框框:
import matplotlib.pyplot as pltplt.text(0.6, 0.7, "I ?", size=50, rotation=30.,ha="center", va="center",bbox=dict(boxstyle="round", # bbox:以框框形式輸出,要帶上參數(shù)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:以框框形式輸出,要帶上參數(shù)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)
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
調(diào)用方式如下:
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)
兩種調(diào)用方式:
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)
參數(shù):
text:str,該參數(shù)是指注釋文本的內(nèi)容
xy:該參數(shù)接受二維元組(float, float),是指要注釋的點(diǎn)。其二維元組所在的坐標(biāo)系由xycoords參數(shù)決定
xytext:注釋文本的坐標(biāo)點(diǎn),也是二維元組,默認(rèn)與xy相同
關(guān)于參數(shù)xycoords:
| ‘figure points’ | Points from the lower left of the figure |
| ‘figure pixels’ | Pixels from the lower left of the figure |
1.7 字體的設(shè)置方法
- 全局字體設(shè)置
- 局部字體設(shè)置
總結(jié):1.1~1.7知識(shí)點(diǎn)匯總
#這是以上學(xué)習(xí)內(nèi)容的總結(jié)案例 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', #右下角的坐標(biāo)在圖的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 數(shù)學(xué)表達(dá)式
使用latex語法即可。
2 tick上的text
#一般繪圖時(shí)會(huì)自動(dòng)創(chuàng)建刻度,而如果通過上面的例子使用set_ticks創(chuàng)建刻度可能會(huì)導(dǎo)致tick的范圍與所繪制圖形的范圍不一致的問題。 #所以在下面的案例中,axs[1]中set_xtick的設(shè)置要與數(shù)據(jù)范圍所對(duì)應(yīng),然后再通過set_xticklabels設(shè)置刻度所對(duì)應(yīng)的標(biāo)簽 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軸的刻度放在數(shù)據(jù)范圍中的哪些位置 axs[1].set_xticklabels(['zero','one', 'two', 'three', 'four', 'five','six'],#設(shè)置刻度對(duì)應(yīng)的標(biāo)簽rotation=30, fontsize='small')#rotation選項(xiàng)設(shè)定x刻度標(biāo)簽傾斜30度。 axs[1].xaxis.set_ticks_position('bottom')#set_ticks_position()方法是用來設(shè)置刻度所在的位置,常用的參數(shù)有bottom、top、both、none print(axs[1].xaxis.get_ticklines()) plt.show()2.1 Tick Locators and Formatters
- 設(shè)置標(biāo)簽的位置
Axis.set_major_locator
Axis.set_minor_locator
- 設(shè)置標(biāo)簽的格式
Axis.set_major_formatter
Axis.set_minor_formatter
2.1.1 Formatters
2. 接收函數(shù)
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()#自動(dòng)分配刻度值的位置
- llocator=plt.IndexLocator(offset=0.5, base=1)#面元間距是1,從0.5開始
- llocator=plt.MultipleLocator(1.5)#將刻度的標(biāo)簽設(shè)置為1.5的倍數(shù)
- llocator=plt.LinearLocator(numticks=5)#線性劃分5等分,4個(gè)刻度
2.1.3 調(diào)整x、y軸的位置
#這個(gè)案例中展示了如何進(jìn)行坐標(biāo)軸的移動(dòng),如何更改刻度值的樣式 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軸上的小標(biāo)改成文字,其中,空格需要增加\,即'\ ',$可將格式更改成數(shù)字模式,如果需要輸入數(shù)學(xué)形式的α,則需要用\轉(zhuǎn)換,即\alpha 如果使用面向?qū)ο蟮拿钸M(jìn)行畫圖,那么下面兩行代碼可以實(shí)現(xiàn)與 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' 獲取現(xiàn)在的軸 ''' ax = plt.gca()是獲取當(dāng)前的axes,其中g(shù)ca代表的是get current axes。 fig=plt.gcf是獲取當(dāng)前的figure,其中g(shù)cf代表的是get current figure。許多函數(shù)都是對(duì)當(dāng)前的Figure或Axes對(duì)象進(jìn)行處理, 例如plt.plot()實(shí)際上會(huì)通過plt.gca()獲得當(dāng)前的Axes對(duì)象ax,然后再調(diào)用ax.plot()方法實(shí)現(xiàn)真正的繪圖。而在本例中則可以通過ax.spines方法獲得當(dāng)前頂部和右邊的軸并將其顏色設(shè)置為不可見 然后將左邊軸和底部的軸所在的位置重新設(shè)置 最后再通過set_ticks_position方法設(shè)置ticks在x軸或y軸的位置,本示例中因所設(shè)置的bottom和left是ticks在x軸或y軸的默認(rèn)值,所以這兩行的代碼也可以不寫 ''' ax.spines['top'].set_color('none') ax.spines['right'].set_color('none') ax.spines['left'].set_position(('data',0)) # data 0:將底部設(shè)置在數(shù)據(jù)的y=0處 ax.spines['bottom'].set_position(('data',0))# data 0:將左部設(shè)置在數(shù)據(jù)的x=0處 ax.xaxis.set_ticks_position('bottom') #設(shè)置ticks在x軸的位置 ax.yaxis.set_ticks_position('left') #設(shè)置ticks在y軸的位置 plt.show()3 Legend
常用的幾個(gè)參數(shù):
(1)設(shè)置圖列位置
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)設(shè)置圖例字體大小
fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
(3)設(shè)置圖例邊框及背景
plt.legend(loc=‘best’,frameon=False) #去掉圖例邊框
plt.legend(loc=‘best’,edgecolor=‘blue’) #設(shè)置圖例邊框顏色
plt.legend(loc=‘best’,facecolor=‘blue’) #設(shè)置圖例背景顏色,若無邊框,參數(shù)無效
(4)設(shè)置圖例標(biāo)題
legend = plt.legend([“CH”, “US”], title=‘China VS Us’)
(5)設(shè)置圖例名字及對(duì)應(yīng)關(guān)系
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參數(shù)設(shè)置圖例所在的位置,title設(shè)置圖例的標(biāo)題,frameon參數(shù)將圖例邊框給去掉添加多個(gè)lengend,plt.gca().add_artist():
#這個(gè)案例是顯示多圖例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,所以會(huì)將l1從legend中給移除 plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1) # 為了保留之前的l1這個(gè)legend,所以必須要通過plt.gca()獲得當(dāng)前的axes,然后將l1作為單獨(dú)的artist plt.gca().add_artist(l1)作業(yè)
總結(jié)
以上是生活随笔為你收集整理的数据可视化组队学习:《Task04 - 文字图例尽眉目》笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作者:陈婷婷(1986-),女,中国科学
- 下一篇: 【2017年第4期】大数据平台的基础能力