搜尋
首頁後端開發Python教學Python中Matplotlib圖像怎麼添加標籤

Python中Matplotlib圖像怎麼添加標籤

May 12, 2023 pm 12:52 PM
pythonmatplotlib

一、新增文字標籤 plt.text()

用於在繪圖過程中,在圖像上指定座標的位置新增文字。需要用到的是plt.text()方法。

其主要的參數有三個:

plt.text(x, y, s)

其中x、y表示傳入點的x和y軸座標。 s表示字串。

要注意的是,這裡的座標,如果設定有xticks、yticks標籤,則指的不是標籤,而是繪圖時x、軸的原始值。

因為參數過多,不再一一解釋,根據程式碼學習其用法。

ha = 'center’表示垂直對齊方式居中,fontsize = 30表示字體大小為30,rotation = -25表示旋轉的角度為-25度。 c 設定顏色,alpha設定透明度。 va表示水平對齊方式。

1. 範例

程式碼在圖像中加入了兩段文本,一段是「旅途中的寬~」的斜體浮水印,透明度為0.4。

另一段則是在折線的每個折點附近標示當天收盤價。

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = range(9)
y = [5.12, 5.15, 5.13, 5.10, 5.2, 5.25, 5.19, 5.24, 5.31]
c = 0.5 * (min(x) + max(x))
d = min(y) + 0.3 * (max(y) - min(y))
# 水印效果
plt.text(c, d, '旅途中的宽~', ha = 'center', fontsize = 30, rotation = -25, c = 'gray', alpha = 0.4)
plt.plot(x, y, label = '股票A收盘价', c = 'r', ls = '-.', marker = 'D', lw = 2)
plt.xticks(x, [
	'2022-03-27', '2022-03-28', '2022-03-29', '2022-03-30',
	'2022-03-31', '2022-04-01', '2022-04-04', '2022-04-05',
	'2022-04-06'], rotation = 45)
plt.title('某股票收盘价时序图')
plt.xlabel('日期')
plt.ylabel('价格')
plt.grid(True)
plt.legend()
# 标出每天的收盘价
for a, b in zip(x, y):
	plt.text(a, b + 0.01, '%.2f' % b, ha = 'center', va = 'bottom', fontsize = 14)
plt.show()

Python中Matplotlib圖像怎麼添加標籤

二、新增註解 plt.annotate()

在上例程式碼的基礎之上,加上註解。註釋即對影像中某一位置的解釋,可以用箭頭來指向。

新增註解使用的是plt.annotate()方法

#其語法中的常用參數如下

plt.annotate(str,xy,xytext,xycoords,arrowcoords)

其中str即註解要使用的字串,即註解文字;xy指被註解的座標點;xytext指註釋文字要寫在的位置;xycoords是被註釋的點的座標系屬性,即以什麼樣的方式描述該點的座標。設定值默為"data",即用(x,y)座標來描述。其他可以選擇的設定值如下,其中figure指的是整個畫布作為一個參考系。而axes則表示僅對於其中的一個axes物件區域。

Python中Matplotlib圖像怎麼添加標籤

arrowprops是一個字典,用來設定箭頭的屬性。寫在這個字典之外的參數都表示的是註釋文本的屬性。

字典內可以設定的值有:

Python中Matplotlib圖像怎麼添加標籤

關於這些參數的進一步解釋:其中箭頭的總長度先是透過被註解點位置座標與註釋由文字位置座標所決定的,可以透過調節參數arrowprops中的shrink鍵來進一步調節箭頭的長度,shrink表示將箭頭縮短的長度佔總長度(被註釋點位置座標與註釋文字位置座標決定的長度)的百分比。不設定shrink時,shrink預設為0,即不縮短。當shrink很大,接近1時,其效果等同於不縮短。

1. 範例

以標出圖中的最低價的點為例。在目標位置加上一個紅色的箭頭,及「最低價」三個字。

其他更多參數,如關於設定註解文字的字體的,c或color表示顏色,fontsize表示字體大小。更多屬性自行了解嘗試。

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = range(9)
y = [5.12, 5.15, 5.13, 5.10, 5.2, 5.25, 5.19, 5.24, 5.31]
c = 0.5 * (min(x) + max(x))
d = min(y) + 0.3 * (max(y) - min(y))
# 仿水印效果
plt.text(c, d, '旅途中的宽', ha = 'center', fontsize = 30, rotation = -25, c = 'gray', alpha = 0.4)
plt.plot(x, y, label = '股票A收盘价', c = 'r', ls = '-.', marker = 'D', lw = 2)
# plt.plot([5.09, 5.13, 5.16, 5.12, 5.09, 5.25, 5.16, 5.20, 5.25], label='股票B收盘价', c='g', ls=':', marker='H', lw=4)
plt.xticks(x, [
    '2022-03-27', '2022-03-28', '2022-03-29', '2022-03-30',
    '2022-03-31', '2022-04-01', '2022-04-04', '2022-04-05',
    '2022-04-06'], rotation = 45)
plt.title('某股票收盘价时序图')
plt.xlabel('日期')
plt.ylabel('价格')
plt.grid(True)
plt.legend()
# 标出每天的收盘价
for a, b in zip(x, y):
    plt.text(a, b + 0.01, '%.3f'% b, ha = 'center', va = 'bottom', fontsize = 9)
# 添加注释
plt.annotate('最低价', (x[y.index(min(y))], min(y)), (x[y.index(min(y))] + 0.5, min(y)), xycoords = 'data',
             arrowprops = dict(facecolor = 'r', shrink = 0.1), c = 'r',fontsize = 15)
plt.show()

Python中Matplotlib圖像怎麼添加標籤

下邊換一個效果呈現,新增的註解箭頭寬度為3,箭頭的頭部寬度為10,長度為20,縮短0.05,且箭頭為綠色,註釋字體為紅色。程式碼範例如下:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x = range(9)
y = [5.12, 5.15, 5.13, 5.10, 5.2, 5.25, 5.19, 5.24, 5.31]
c = 0.5 * (min(x) + max(x))
d = min(y) + 0.3 * (max(y)-min(y))
plt.plot(x, y, label = '股票A收盘价', c = 'k', ls = '-.', marker = 'D', lw = 2)
plt.xticks(x, [
    '2022-03-27', '2022-03-28', '2022-03-29', '2022-03-30',
    '2022-03-31', '2022-04-01', '2022-04-04', '2022-04-05',
    '2022-04-06'], rotation = 45)
plt.title('某股票收盘价时序图')
plt.xlabel('日期')
plt.ylabel('价格')
plt.grid(True)
plt.legend()
# 标出每天的收盘价
for a, b in zip(x, y):
    plt.text(a, b+0.01, '%.1f'%b, ha='center', va='bottom', fontsize=9)
plt.text(c, d, '旅途中的宽', ha = 'center', fontsize = 50, rotation = -25, c = 'r')
plt.annotate('最低价', (x[y.index(min(y))], min(y)), (x[y.index(min(y))] + 2, min(y)), xycoords = 'data',
             arrowprops = dict(width = 3, headwidth = 10, headlength = 20, facecolor = 'g', shrink = 0.05), c = 'r',fontsize = 20)
plt.show()

Python中Matplotlib圖像怎麼添加標籤

以上是Python中Matplotlib圖像怎麼添加標籤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能