python可视化添加文本_python Matplotlib基础--如何添加文本和标注
創(chuàng)建一個(gè)優(yōu)秀的可視化圖表的關(guān)鍵在于引導(dǎo)讀者,讓他們能理解圖表所講述的故事。在一些情況下,這個(gè)故事可以通過(guò)純圖像的方式表達(dá),不需要額外添加文字,但是在另外一些情況中,圖表需要文字的提示和標(biāo)簽才能將故事講好。也許標(biāo)注最基本的類(lèi)型就是圖表的標(biāo)簽和標(biāo)題,但是其中的選項(xiàng)參數(shù)卻有很多。讓我們?cè)诒竟?jié)中使用一些數(shù)據(jù)來(lái)創(chuàng)建可視化圖表并標(biāo)注這些圖表來(lái)表達(dá)這些有趣的信息。首先還是需要將要用到的模塊和包導(dǎo)入pycharm:
import matplotlib.pyplot as plt
import matplotlib as mpl
plt.style.use('seaborn-whitegrid')
import numpy as np
import pandas as pd
例子:節(jié)假日對(duì)美國(guó)出生率的影響
我們先按照前面的方式進(jìn)行同樣的數(shù)據(jù)清洗程序,然后以圖表展示這個(gè)結(jié)果:
births = pd.read_csv(r'd:\python\github學(xué)習(xí)材料\python數(shù)據(jù)科學(xué)手冊(cè)\data\births.csv')
quartiles = np.percentile(births['births'], [25, 50, 75])
mu, sig = quartiles[1], 0.74 * (quartiles[2] - quartiles[0])
births = births.query('(births > @mu - 5 * @sig) & (births < @mu + 5 * @sig)')
births['day'] = births['day'].astype(int)
births.index = pd.to_datetime(10000 * births.year +
100 * births.month +
births.day, format='%y%m%d')
births_by_date = births.pivot_table('births',
[births.index.month, births.index.day])
births_by_date.index = [pd.datetime(2012, month, day)
for (month, day) in births_by_date.index]
fig, ax = plt.subplots(figsize=(12, 4))
births_by_date.plot(ax=ax);
當(dāng)我們繪制了這樣的圖表來(lái)表達(dá)數(shù)據(jù)時(shí),如果我們能對(duì)一些圖表的特性作出標(biāo)注來(lái)吸引讀者的注意力通常是非常有幫助的。這可以通過(guò)調(diào)用plt.text或ax.text函數(shù)來(lái)實(shí)現(xiàn),它們可以在某個(gè)特定的 x,y 軸位置輸出一段文字:
fig, ax = plt.subplots(figsize=(12, 4))
births_by_date.plot(ax=ax)
# 在折線的特殊位置標(biāo)注文字
style = dict(size=10, color='gray')
ax.text('2012-1-1', 3950, "new year's day", **style)
ax.text('2012-7-4', 4250, "independence day", ha='center', **style)
ax.text('2012-9-4', 4850, "labor day", ha='center', **style)
ax.text('2012-10-31', 4600, "halloween", ha='right', **style)
ax.text('2012-11-25', 4450, "thanksgiving", ha='center', **style)
ax.text('2012-12-25', 3850, "christmas ", ha='right', **style)
# 設(shè)置標(biāo)題和y軸標(biāo)簽
ax.set(title='usa births by day of year (1969-1988)',
ylabel='average daily births')
# 設(shè)置x軸標(biāo)簽月份居中
ax.xaxis.set_major_locator(mpl.dates.monthlocator())
ax.xaxis.set_minor_locator(mpl.dates.monthlocator(bymonthday=15))
ax.xaxis.set_major_formatter(plt.nullformatter())
ax.xaxis.set_minor_formatter(mpl.dates.dateformatter('%h'));
ax.text方法接收 x 位置、y 位置、一個(gè)字符串和額外可選的關(guān)鍵字參數(shù)可以用來(lái)設(shè)置顏色、大小、樣式、對(duì)齊等文本格式。上面我們使用了ha='right'和ha='center',這里的ha是*hirizonal alignment(水平對(duì)齊)*的縮寫(xiě)。要查閱更多的可用參數(shù),請(qǐng)查看plt.text()和mpl.text.text()的文檔字符串內(nèi)容。
轉(zhuǎn)換和文本位置
在剛才的例子中,我們將文字標(biāo)注根據(jù)數(shù)據(jù)位置進(jìn)行了定位。有些時(shí)候我們需要將文字標(biāo)注獨(dú)立于數(shù)據(jù)位置而根據(jù)圖表位置進(jìn)行定位。matplotlib 通過(guò)轉(zhuǎn)換完成這項(xiàng)工作。
任何的圖形顯示框架都需要在坐標(biāo)系統(tǒng)之間進(jìn)行轉(zhuǎn)換的機(jī)制。例如,一個(gè)數(shù)據(jù)點(diǎn)位于??被轉(zhuǎn)換為圖表中的某個(gè)位置,進(jìn)而轉(zhuǎn)換為屏幕上顯示的像素。這樣的坐標(biāo)轉(zhuǎn)換在數(shù)學(xué)上都相對(duì)來(lái)說(shuō)比較直接,,而且 matplotlib 提供了一系列的工具實(shí)現(xiàn)了轉(zhuǎn)換(這些工具可以在matplotlib.transforms模塊中找到)。
一般來(lái)說(shuō),用戶(hù)很少需要關(guān)注這些轉(zhuǎn)換的細(xì)節(jié),但是當(dāng)考慮將文本在圖表上展示時(shí),這些知識(shí)卻比較有用。在這種情況中,下面三種定義好的轉(zhuǎn)換是比較有用的:
ax.transdata:與數(shù)據(jù)坐標(biāo)相關(guān)的轉(zhuǎn)換
ax.tranaxes:與 axes 尺寸相關(guān)的轉(zhuǎn)換(單位是 axes 的寬和高)
ax.tranfigure:與 figure 尺寸相關(guān)的轉(zhuǎn)換(單位是 figure 的寬和高)
下面我們來(lái)看看使用這些轉(zhuǎn)換將文字寫(xiě)在圖表中不同位置的例子:
fig, ax = plt.subplots(facecolor='lightgray')
ax.axis([0, 10, 0, 10])
# transform=ax.transdata是默認(rèn)的,這里寫(xiě)出來(lái)是為了明確對(duì)比
ax.text(1, 5, ". data: (1, 5)", transform=ax.transdata)
ax.text(0.5, 0.1, ". axes: (0.5, 0.1)", transform=ax.transaxes)
ax.text(0.2, 0.2, ". figure: (0.2, 0.2)", transform=fig.transfigure);
注意默認(rèn)情況下,文字是在指定坐標(biāo)位置靠左對(duì)齊的:這里每個(gè)字符串開(kāi)始的"."的位置就是每種轉(zhuǎn)換的坐標(biāo)位置。
transdata坐標(biāo)給定的是通常使用的 x 和 y 軸坐標(biāo)位置。transaxes坐標(biāo)給定的是從 axes 左下角開(kāi)始算起(白色區(qū)域)的坐標(biāo)位置,使用的是寬度和長(zhǎng)度的占比。transfigure坐標(biāo)類(lèi)似,給定的是從 figure 左下角開(kāi)始算起(灰色區(qū)域)的坐標(biāo)位置,使用的也是寬度和長(zhǎng)度的占比。
因此如果我們改變了軸的最大長(zhǎng)度,只有transdata坐標(biāo)會(huì)收到影響,其他兩個(gè)還是保持在相同位置:
ax.set_xlim(0, 2)
ax.set_ylim(-6, 6)
fig
這個(gè)變化可以通過(guò)動(dòng)態(tài)改變軸的最大長(zhǎng)度看的更加清楚:如果你在 notebook 執(zhí)行這段代碼,你可以將%matplotlib inline改為%matplotlib notebook,然后使用圖表的菜單來(lái)交互式的改變圖表。
箭頭和標(biāo)注
除了刻度標(biāo)簽和文字標(biāo)簽,另一種常用的標(biāo)注是箭頭。
在 matplotlib 中繪制箭頭通常比你想象的難得多。雖然有plt.arrow()函數(shù),作者不建議使用它:這個(gè)函數(shù)繪制的箭頭是一個(gè) svg 對(duì)象,因此在圖表使用不同的比例的情況會(huì)產(chǎn)生問(wèn)題,結(jié)果通常不能讓用戶(hù)滿(mǎn)意。因此,作者建議使用plt.annotate()函數(shù)。這個(gè)函數(shù)會(huì)繪制一些文字以及一個(gè)箭頭,并且箭頭可以非常靈活的進(jìn)行配置。
下面我們提供一些參數(shù)來(lái)使用annotate函數(shù):
fig, ax = plt.subplots()
x = np.linspace(0, 20, 1000)
ax.plot(x, np.cos(x))
ax.axis('equal')
ax.annotate('local maximum', xy=(6.28, 1), xytext=(10, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
ax.annotate('local minimum', xy=(5 * np.pi, -1), xytext=(2, -6),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle3,anglea=0,angleb=-90"));
箭頭的樣式是使用箭頭屬性字典值進(jìn)行控制的,里面有很多可用的參數(shù)。這些參數(shù)在 matplotlib 的在線文檔中已經(jīng)有了很詳細(xì)的說(shuō)明,因此在這里就不將這部分內(nèi)容重復(fù)介紹一遍了。我們?cè)谇懊娉錾蕡D上再使用一些參數(shù)進(jìn)行更多的說(shuō)明:
fig, ax = plt.subplots(figsize=(12, 4))
births_by_date.plot(ax=ax)
# 為圖表添加標(biāo)注
ax.annotate("new year's day", xy=('2012-1-1', 4100),? xycoords='data',
xytext=(50, -30), textcoords='offset points',
arrowprops=dict(arrowstyle="->",
connectionstyle="arc3,rad=-0.2"))
ax.annotate("independence day", xy=('2012-7-4', 4250),? xycoords='data',
bbox=dict(boxstyle="round", fc="none", ec="gray"),
xytext=(10, -40), textcoords='offset points', ha='center',
arrowprops=dict(arrowstyle="->"))
ax.annotate('labor day', xy=('2012-9-4', 4850), xycoords='data', ha='center',
xytext=(0, -20), textcoords='offset points')
ax.annotate('', xy=('2012-9-1', 4850), xytext=('2012-9-7', 4850),
xycoords='data', textcoords='data',
arrowprops={'arrowstyle': '|-|,widtha=0.2,widthb=0.2', })
ax.annotate('halloween', xy=('2012-10-31', 4600),? xycoords='data',
xytext=(-80, -40), textcoords='offset points',
arrowprops=dict(arrowstyle="fancy",
fc="0.6", ec="none",
connectionstyle="angle3,anglea=0,angleb=-90"))
ax.annotate('thanksgiving', xy=('2012-11-25', 4500),? xycoords='data',
xytext=(-120, -60), textcoords='offset points',
bbox=dict(boxstyle="round4,pad=.5", fc="0.9"),
arrowprops=dict(arrowstyle="->",
connectionstyle="angle,anglea=0,angleb=80,rad=20"))
ax.annotate('christmas', xy=('2012-12-25', 3850),? xycoords='data',
xytext=(-30, 0), textcoords='offset points',
size=13, ha='right', va="center",
bbox=dict(boxstyle="round", alpha=0.1),
arrowprops=dict(arrowstyle="wedge,tail_width=0.5", alpha=0.1));
# 設(shè)置圖表標(biāo)題和坐標(biāo)軸標(biāo)記
ax.set(title='usa births by day of year (1969-1988)',
ylabel='average daily births')
# 設(shè)置月份坐標(biāo)居中顯示
ax.xaxis.set_major_locator(mpl.dates.monthlocator())
ax.xaxis.set_minor_locator(mpl.dates.monthlocator(bymonthday=15))
ax.xaxis.set_major_formatter(plt.nullformatter())
ax.xaxis.set_minor_formatter(mpl.dates.dateformatter('%h'));
ax.set_ylim(3600, 5400);
上圖中箭頭和文字框都非常詳盡了:可以看出你幾乎可以使用plt.annotate創(chuàng)建任何你想要的箭頭樣式。不幸的是,這意味著這種特性都需要手工進(jìn)行調(diào)整,因此如果需要獲得印刷質(zhì)量的圖像,這將是一個(gè)非常耗費(fèi)時(shí)間的工作。最后,必須指出,上述這種多種樣式混合的方式來(lái)展現(xiàn)數(shù)據(jù)肯定不是最佳實(shí)踐,這里只是為了盡可能多的介紹可用的參數(shù)。
更多關(guān)于 matplotlib 的箭頭和標(biāo)注樣式的討論和例子可以訪問(wèn) matplotlib gallery。
以上就是python matplotlib基礎(chǔ)--如何添加文本和標(biāo)注的詳細(xì)內(nèi)容,更多關(guān)于python matplotlib添加文本和標(biāo)注的資料請(qǐng)關(guān)注萬(wàn)仟網(wǎng)其它相關(guān)文章!
希望與廣大網(wǎng)友互動(dòng)??
點(diǎn)此進(jìn)行留言吧!
總結(jié)
以上是生活随笔為你收集整理的python可视化添加文本_python Matplotlib基础--如何添加文本和标注的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 系统分析师通过率_软考5个高级难度最小的
- 下一篇: python代码异常对照表格_Pytho