matplotlib xticks 基于 旋转_咬文嚼字——对matplotlib的文字绘图总结
/?導讀?/
我們經常面臨在畫圖時的文字標注,本文從圖片、坐標軸、坐標值等層面講起,對matplotlib的文字繪圖功能進行總結說明。
Figure和Axes上的文本
Matplotlib具有廣泛的文本支持,包括對數學表達式的支持、對柵格和矢量輸出的TrueType支持、具有任意旋轉的換行分隔文本以及Unicode支持。
下面通過text,figures,axes,suptitle等案例進行學習。
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.font_manager import FontPropertiesimport numpy as np#fontdict學習的案例#學習的過程中請嘗試更換不同的fontdict字典的內容,以便于更好的掌握#---------設置字體樣式,分別是字體,顏色,寬度,大小font1 = {'family': 'SimSun',#華文楷體 'alpha':0.7,#透明度 '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('震蕩曲線', 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()可以看到對圖片的橫縱坐標進行字體顏色、格式、大小進行了設置。值得注意的是圖片中公式的插入。大家平時在寫論文時,大多涉及復雜的公式,對于Word愛好者來說,一般采用墨跡公式,這里可以學習Python寫入,還可以通過博客的數學公式編輯和Latex。
#文本屬性的輸入一種是通過**kwargs屬性這種方式,一種是通過操作 matplotlib.font_manager.FontProperties 方法#該案例中對于x_label采用**kwargs調整字體屬性,y_label則采用 matplotlib.font_manager.FontProperties 方法調整字體屬性#該鏈接是FontProperties方法的介紹 https://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontPropertiesx1 = 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()這里是對坐標進行設置,以及調整標題的位置。此外,這里引用了font = FontProperties(),該參數是可選參數,如果該參數被指定,字體的大小將從該參數的默認值中提取。這里貼出官方介紹文檔:
https://matplotlib.org/api/font_manager_api.html#matplotlib.font_manager.FontProperties
import matplotlib.pyplot as pltdef demo_con_style(ax, connectionstyle): x1, y1 = 0.3, 0.2 x2, y2 = 0.8, 0.6 ax.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()相比于前面的圖片,上面的這張在科研中見的很少,在這里貼出代碼,后續有需要再過來復讀。
import numpy as npimport 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, 0xdisplay, 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,向上72pointsax.annotate('data = (%.1f, %.1f)'%(xdata, ydata), (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points', bbox=bbox, arrowprops=arrowprops)# xycoords以繪圖區左下角為參考,單位為像素# 注釋文本參考被注釋點設置偏移量,向右0.5*72points,向下72pointsdisp = 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()這里同樣是annotate的應用,箭頭指向可以標明變化的位置,論文作圖時可以參考。下面是一些參數說明
text:str,該參數是指注釋文本的內容
xy:該參數接受二維元組(float, float),是指要注釋的點。其二維元組所在的坐標系由xycoords參數決定
xytext:注釋文本的坐標點,也是二維元組,默認與xy相同
對于論文畫圖時需要查閱所需文字中英文形式時,可參考下面鏈接
https://www.cnblogs.com/chendc/p/9298832.html
下面這個是對上方學習內容的總結案例
import matplotlibimport matplotlib.pyplot as pltfig = plt.figure()ax = fig.add_subplot(111)fig.subplots_adjust(top=0.85)# 分別在figure和subplot上設置titlefig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')ax.set_title('axes title')ax.set_xlabel('xlabel')ax.set_ylabel('ylabel')# 設置x-axis和y-axis的范圍都是[0, 10]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', 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()Tick Locators and Formatters
設置tick(刻度)和ticklabel(刻度標簽)也是可視化中經常需要操作的步驟,matplotlib既提供了自動生成刻度和刻度標簽的模式(默認狀態),同時也提供了許多讓使用者靈活設置的方式。
下面是幾個案例展示,體會刻度設置的不同之處
import matplotlib.pyplot as pltimport numpy as npimport matplotlibx1 = np.linspace(0.0, 5.0, 100)y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)# 使用axis的set_ticks方法手動設置標簽位置的例子,該案例中由于tick設置過大,所以會影響繪圖美觀,不建議用此方式進行設置tickfig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)axs[0].plot(x1, y1)axs[1].plot(x1, y1)axs[1].xaxis.set_ticks(np.arange(0., 10.1, 2.))plt.show()# 使用axis的set_ticklabels方法手動設置標簽格式的例子fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)axs[0].plot(x1, y1)axs[1].plot(x1, y1)ticks = np.arange(0., 8.1, 2.)tickla = [f'{tick:1.2f}' for tick in ticks]axs[1].xaxis.set_ticks(ticks)axs[1].xaxis.set_ticklabels(tickla)plt.show()#一般繪圖時會自動創建刻度,而如果通過上面的例子使用set_ticks創建刻度可能會導致tick的范圍與所繪制圖形的范圍不一致的問題。#所以在下面的案例中,axs[1]中set_xtick的設置要與數據范圍所對應,然后再通過set_xticklabels設置刻度所對應的標簽import numpy as npimport matplotlib.pyplot as pltfig, 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、noneprint(axs[1].xaxis.get_ticklines())plt.show()# 接收字符串格式的例子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()相比于上述的案例,下面的這個注釋更多,可讀性更高,主要是定義的函數相比更簡單。這個案例中展示了如何進行坐標軸的移動,如何更改刻度值的樣式
import matplotlib.pyplot as pltimport numpy as npx = np.linspace(-3,3,50)y1 = 2*x+1y2 = x**2plt.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))ax.spines['bottom'].set_position(('data',0))#axes 百分比ax.xaxis.set_ticks_position('bottom') #設置ticks在x軸的位置ax.yaxis.set_ticks_position('left') #設置ticks在y軸的位置plt.show()legend(圖例)
這部分主要介紹圖例的一些相關術語
legend entry(圖例條目)
圖例有一個或多個legend entries組成。一個entry由一個key和一個label組成。
legend key(圖例鍵)
每個 legend label左面的colored/patterned marker(彩色/圖案標記)
legend label(圖例標簽)
描述由key來表示的handle的文本
legend?handle(圖例句柄)
用于在圖例中生成適當圖例條目的原始對象
以下面這個圖為例,右側的方框中的共有兩個legend entry;兩個legend key,分別是一個藍色和一個黃色的legend key;兩個legend label,一個名為‘Line up’和一個名為‘Line Down’的legend label
作業
1.嘗試在一張圖中運用所講過的功能,對title、text、xlable、ylabel、數學表達式、tick and ticklabel、legend進行詳細的設計。
import numpy as npimport matplotlib.pyplot as pltimport pandas as pdfrom matplotlib.font_manager import FontPropertiesimport numpy as npfont1 = {'family': 'SimSun', 'alpha':0.7,'color': 'red', 'weight': 'normal', 'size': 20}font2 = {'family': 'Times New Roman', 'color': 'black', 'weight': 'normal', 'size': 8 }font3 = {'family': 'Tw Cen MT', 'color': 'black', 'weight': 'bold', 'size': 14 }font4 = {'family': 'Colonna MT', 'color': 'black','weight': 'normal','size': 14, }x = np.linspace(0.0, 5.0, 100)y = np.cos(2*np.pi*x) * np.exp(-x/3)y1= np.sin(2*np.pi*x) * np.exp(-x/5)plt.plot(x, y, '--',label='$\cos(2 \pi x) \exp(-x/3)$')plt.plot(x, y1, '--',label='$\sin(2 \pi x) \exp(-x/5)$')plt.title('作業圖形', fontdict=font1)plt.xlabel('Y=time (s)', fontdict=font3)plt.ylabel('X=voltage(mv)', fontdict=font4)plt.legend()plt.subplots_adjust(left=0.15)plt.show()參考:Datawhale第20期數據可視化講義
鏈接:http://datawhale.club/t/topic/543
總結
以上是生活随笔為你收集整理的matplotlib xticks 基于 旋转_咬文嚼字——对matplotlib的文字绘图总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在以下说法错误的是_关于犬麻醉常见的错误
- 下一篇: javascript 设计模式_开发者都