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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

matplotlib xticks 基于 旋转_咬文嚼字——对matplotlib的文字绘图总结

發(fā)布時間:2025/3/15 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 matplotlib xticks 基于 旋转_咬文嚼字——对matplotlib的文字绘图总结 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

/?導(dǎo)讀?/

我們經(jīng)常面臨在畫圖時的文字標注,本文從圖片、坐標軸、坐標值等層面講起,對matplotlib的文字繪圖功能進行總結(jié)說明。

Figure和Axes上的文本

Matplotlib具有廣泛的文本支持,包括對數(shù)學(xué)表達式的支持、對柵格和矢量輸出的TrueType支持、具有任意旋轉(zhuǎn)的換行分隔文本以及Unicode支持。

下面通過text,figures,axes,suptitle等案例進行學(xué)習(xí)。

import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.font_manager import FontPropertiesimport numpy as np#fontdict學(xué)習(xí)的案例#學(xué)習(xí)的過程中請嘗試更換不同的fontdict字典的內(nèi)容,以便于更好的掌握#---------設(shè)置字體樣式,分別是字體,顏色,寬度,大小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, }#-----------四種不同字體顯示風(fēng)格-----#-------建立函數(shù)----------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)#---------設(shè)置坐標標簽plt.xlabel('Y=time (s)', fontdict=font3)plt.ylabel('X=voltage(mv)', fontdict=font4)# 調(diào)整圖像邊距plt.subplots_adjust(left=0.15)plt.show()

可以看到對圖片的橫縱坐標進行字體顏色、格式、大小進行了設(shè)置。值得注意的是圖片中公式的插入。大家平時在寫論文時,大多涉及復(fù)雜的公式,對于Word愛好者來說,一般采用墨跡公式,這里可以學(xué)習(xí)Python寫入,還可以通過博客的數(shù)學(xué)公式編輯和Latex。

#文本屬性的輸入一種是通過**kwargs屬性這種方式,一種是通過操作 matplotlib.font_manager.FontProperties 方法#該案例中對于x_label采用**kwargs調(diào)整字體屬性,y_label則采用 matplotlib.font_manager.FontProperties 方法調(diào)整字體屬性#該鏈接是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()

這里是對坐標進行設(shè)置,以及調(diào)整標題的位置。此外,這里引用了font = FontProperties(),該參數(shù)是可選參數(shù),如果該參數(shù)被指定,字體的大小將從該參數(shù)的默認值中提取。這里貼出官方介紹文檔:

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()

相比于前面的圖片,上面的這張在科研中見的很少,在這里貼出代碼,后續(xù)有需要再過來復(fù)讀。

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)#設(shè)置x軸的范圍ax.set_ylim(-1, 1)#設(shè)置x軸的范圍# 被注釋點的數(shù)據(jù)軸坐標和所在的像素xdata, ydata = 5, 0xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))# 設(shè)置注釋文本的樣式和箭頭的樣式bbox = dict(boxstyle="round", fc="0.8")arrowprops = dict( arrowstyle = "->", connectionstyle = "angle,angleA=0,angleB=90,rad=10")# 設(shè)置偏移量offset = 72# xycoords默認為'data'數(shù)據(jù)軸坐標,對坐標點(5,0)添加注釋# 注釋文本參考被注釋點設(shè)置偏移量,向左2*72points,向上72pointsax.annotate('data = (%.1f, %.1f)'%(xdata, ydata), (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points', bbox=bbox, arrowprops=arrowprops)# xycoords以繪圖區(qū)左下角為參考,單位為像素# 注釋文本參考被注釋點設(shè)置偏移量,向右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的應(yīng)用,箭頭指向可以標明變化的位置,論文作圖時可以參考。下面是一些參數(shù)說明

text:str,該參數(shù)是指注釋文本的內(nèi)容

xy:該參數(shù)接受二維元組(float, float),是指要注釋的點。其二維元組所在的坐標系由xycoords參數(shù)決定

xytext:注釋文本的坐標點,也是二維元組,默認與xy相同

對于論文畫圖時需要查閱所需文字中英文形式時,可參考下面鏈接

https://www.cnblogs.com/chendc/p/9298832.html


下面這個是對上方學(xué)習(xí)內(nèi)容的總結(jié)案例

import matplotlibimport matplotlib.pyplot as pltfig = plt.figure()ax = fig.add_subplot(111)fig.subplots_adjust(top=0.85)# 分別在figure和subplot上設(shè)置titlefig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')ax.set_title('axes title')ax.set_xlabel('xlabel')ax.set_ylabel('ylabel')# 設(shè)置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

設(shè)置tick(刻度)和ticklabel(刻度標簽)也是可視化中經(jīng)常需要操作的步驟,matplotlib既提供了自動生成刻度和刻度標簽的模式(默認狀態(tài)),同時也提供了許多讓使用者靈活設(shè)置的方式。

下面是幾個案例展示,體會刻度設(shè)置的不同之處

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方法手動設(shè)置標簽位置的例子,該案例中由于tick設(shè)置過大,所以會影響繪圖美觀,不建議用此方式進行設(shè)置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方法手動設(shè)置標簽格式的例子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()

#一般繪圖時會自動創(chuàng)建刻度,而如果通過上面的例子使用set_ticks創(chuàng)建刻度可能會導(dǎo)致tick的范圍與所繪制圖形的范圍不一致的問題。#所以在下面的案例中,axs[1]中set_xtick的設(shè)置要與數(shù)據(jù)范圍所對應(yīng),然后再通過set_xticklabels設(shè)置刻度所對應(yīng)的標簽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軸的刻度放在數(shù)據(jù)范圍中的哪些位置axs[1].set_xticklabels(['zero','one', 'two', 'three', 'four', 'five','six'],#設(shè)置刻度對應(yīng)的標簽 rotation=30, fontsize='small')#rotation選項設(shè)定x刻度標簽傾斜30度。axs[1].xaxis.set_ticks_position('bottom')#set_ticks_position()方法是用來設(shè)置刻度所在的位置,常用的參數(shù)有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()

相比于上述的案例,下面的這個注釋更多,可讀性更高,主要是定義的函數(shù)相比更簡單。這個案例中展示了如何進行坐標軸的移動,如何更改刻度值的樣式

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軸上的小標改成文字,其中,空格需要增加\,即'\ ',$可將格式更改成數(shù)字模式,如果需要輸入數(shù)學(xué)形式的α,則需要用\轉(zhuǎn)換,即\alpha如果使用面向?qū)ο蟮拿钸M行畫圖,那么下面兩行代碼可以實現(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ù)都是對當(dāng)前的Figure或Axes對象進行處理,例如plt.plot()實際上會通過plt.gca()獲得當(dāng)前的Axes對象ax,然后再調(diào)用ax.plot()方法實現(xiàn)真正的繪圖。而在本例中則可以通過ax.spines方法獲得當(dāng)前頂部和右邊的軸并將其顏色設(shè)置為不可見然后將左邊軸和底部的軸所在的位置重新設(shè)置最后再通過set_ticks_position方法設(shè)置ticks在x軸或y軸的位置,本示例中因所設(shè)置的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') #設(shè)置ticks在x軸的位置ax.yaxis.set_ticks_position('left') #設(shè)置ticks在y軸的位置plt.show()

legend(圖例)

這部分主要介紹圖例的一些相關(guān)術(shù)語

legend entry(圖例條目)

圖例有一個或多個legend entries組成。一個entry由一個key和一個label組成。

legend key(圖例鍵)

每個 legend label左面的colored/patterned marker(彩色/圖案標記)

legend label(圖例標簽)

描述由key來表示的handle的文本

legend?handle(圖例句柄)

用于在圖例中生成適當(dāng)圖例條目的原始對象

以下面這個圖為例,右側(cè)的方框中的共有兩個legend entry;兩個legend key,分別是一個藍色和一個黃色的legend key;兩個legend label,一個名為‘Line up’和一個名為‘Line Down’的legend label

作業(yè)

1.嘗試在一張圖中運用所講過的功能,對title、text、xlable、ylabel、數(shù)學(xué)表達式、tick and ticklabel、legend進行詳細的設(shè)計。

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('作業(yè)圖形', 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期數(shù)據(jù)可視化講義

鏈接:http://datawhale.club/t/topic/543

總結(jié)

以上是生活随笔為你收集整理的matplotlib xticks 基于 旋转_咬文嚼字——对matplotlib的文字绘图总结的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 一区二区三区视频观看 | 欧美性videos高清精品 | 免费三片在线观看网站v888 | 欧美三区四区 | wwwxxx在线观看 | 精品亚洲国产成av人片传媒 | 人妻一区二区三区四区五区 | 麻豆区1免费 | 久久字幕 | 一级黄色免费 | 日本香蕉视频 | 伊人手机在线视频 | 极品五月天 | 大尺度摸揉捏胸床戏视频 | 国产福利电影在线 | www.黄色片.com| 91精品国产99久久久久久红楼 | 亚洲精品在线91 | 久久久久久高清 | 色人人 | 国产乱了高清露脸对白 | 一区二区在线观看av | 激情六月综合 | www午夜| 永久免费视频网站直接看 | 日本韩国欧美 | 九色蝌蚪9l视频蝌蚪9l视频 | 五月伊人网 | 亚洲自拍偷拍第一页 | 久久久久欧美 | 亚洲成人第一页 | av在线播放中文字幕 | 在线观看麻豆视频 | 国产成人精品一区二区三区四区 | 亚洲一区二区三区免费视频 | 国产欧美激情在线观看 | 永久精品视频 | 丁香久久| 超碰在线免费看 | 拔插拔插海外华人永久免费 | 日本黄色录像 | 国产午夜福利片 | 成熟妇人a片免费看网站 | 大学生高潮无套内谢视频 | 亚洲双插 | 操操日日 | 欧美日韩一区二区三区国产精品成人 | 中文天堂在线观看 | 诱惑av| 久草久 | 风间由美一区二区三区 | 天海翼视频在线观看 | 亚洲乱码中文字幕 | 国产女人和拘做受视频免费 | 午夜免费av | 亚洲综合影院 | 91久久网| 亚洲 另类 春色 国产 | 亚洲美免无码中文字幕在线 | 色综合色综合色综合 | 日韩欧美中文字幕一区 | 成人三级电影网站 | 欧美人妖老妇 | 欧美 日韩 国产 在线观看 | 国产三级大片 | 男人操女人逼逼视频 | 中文字幕av一区二区三区人妻少妇 | 国产精品一区二区免费在线观看 | 伊人色网 | 亚洲永久免费视频 | 欧美日韩一卡二卡三卡 | 中文字幕在线1 | 色视频在线观看 | 精品人妻一区二区三区久久夜夜嗨 | 激情伊人 | 美女啪啪网 | 91精品国产高清91久久久久久 | 欧美12--15处交性娇小 | 男人天堂成人 | 欧美精品乱人伦久久久久久 | 男女男精品网站 | 99精品视频免费观看 | 欧美永久 | 黄色爱爱视频 | 亚洲自拍另类 | 午夜免费观看 | 香蕉av一区 | 成人97| 国产亚洲一区二区三区在线观看 | 精品色图 | 91福利免费视频 | 亚洲熟伦熟女新五十路熟妇 | 色丁香六月 | 免费观看美女裸体网站 | 久久综合第一页 | 亚洲操图 | 性xxxfllreexxx少妇 | 少妇熟女高潮流白浆 | 波多野吉衣一二三区乱码 |