数据可视化组队学习:《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確定默認值。
返回值:此方法返回作為創建的文本實例的文本。
給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)
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相同
關于參數xycoords:
| ‘figure points’ | Points from the lower left of the figure |
| ‘figure pixels’ | Pixels from the lower left of the figure |
1.7 字體的設置方法
- 全局字體設置
- 局部字體設置
總結: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
2. 接收函數
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個刻度
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)作業
總結
以上是生活随笔為你收集整理的数据可视化组队学习:《Task04 - 文字图例尽眉目》笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 作者:陈婷婷(1986-),女,中国科学
- 下一篇: 【2017年第4期】大数据平台的基础能力