共計 534 個字符,預(yù)計需要花費 2 分鐘才能閱讀完成。
在 Python 中,可以使用 Matplotlib 庫的 annotate()
函數(shù)來添加數(shù)據(jù)標(biāo)簽。以下是一個例子:
import matplotlib.pyplot as plt
# 數(shù)據(jù)
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
# 繪制折線圖
plt.plot(x, y)
# 添加數(shù)據(jù)標(biāo)簽
for i, j in zip(x, y):
plt.annotate(str(j), xy=(i, j), xytext=(10, -10), textcoords='offset points')
# 顯示圖形
plt.show()
在上面的例子中,我們首先定義了 x 和 y 軸的數(shù)據(jù),然后使用 plot()
函數(shù)繪制了折線圖。接下來,使用 annotate()
函數(shù)循環(huán)遍歷數(shù)據(jù)點,并在每個數(shù)據(jù)點的位置添加標(biāo)簽。annotate()
函數(shù)的參數(shù)說明:
str(j)
:標(biāo)簽文本內(nèi)容,用str()
將數(shù)據(jù)點轉(zhuǎn)換為字符串。xy=(i, j)
:標(biāo)簽的位置,即數(shù)據(jù)點的坐標(biāo)。xytext=(10, -10)
:文本的偏移量,即標(biāo)簽文本相對于數(shù)據(jù)點的偏移量。textcoords='offset points'
:偏移量的參考坐標(biāo)系,設(shè)置為 ’offset points’ 表示偏移量是相對于點的。
最后,使用 show()
函數(shù)顯示圖形。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完