Matplotlib 中的 Legend 圖例、Annotation 標註、Tick 能見度

一、Legend 圖例

添加圖例

matplotlib 中的 legend 圖例就是爲了幫我們展示出每個數據對應的圖像名稱. 更好的讓讀者認識到你的數據結構.

上次我們瞭解到關於座標軸設置方面的一些內容,代碼如下:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y1 = 2*x + 1
y2 = x**2

plt.figure()
#set x limits
plt.xlim((-1, 2))
plt.ylim((-2, 3))

# set new sticks
new_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)
# set tick labels
plt.yticks([-2, -1.8, -1, 1.22, 3],
           [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])

本節中我們將對圖中的兩條線繪製圖例,首先我們設置兩條線的類型等信息(藍色實線與紅色虛線).

# set line syles
l1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')

legend將要顯示的信息來自於上面代碼中的 label. 所以我們只需要簡單寫下一下代碼, plt 就能自動的爲我們添加圖例.

plt.legend(loc='upper right')

參數 loc=‘upper right’ 表示圖例將添加在圖中的右上角.

Legend 圖例

調整位置和名稱

如果我們想單獨修改之前的 label 信息, 給不同類型的線條設置圖例信息. 我們可以在 plt.legend 輸入更多參數. 如果以下面這種形式添加 legend, 我們需要確保, 在上面的代碼 plt.plot(x, y2, label=‘linear line’) 和 plt.plot(x, y1, label=‘square line’) 中有用變量 l1 和 l2 分別存儲起來. 而且需要注意的是 l1, l2,要以逗號結尾, 因爲plt.plot() 返回的是一個列表.

plt.legend(handles=[l1, l2], labels=['up', 'down'],  loc='best')

這樣我們就能分別重新設置線條對應的 label 了.

最後我們得到帶有圖例信息的圖片.

Legend 圖例

其中’loc’參數有多種,’best’表示自動分配最佳位置,其餘的如下:

 'best' : 0,          
 'upper right'  : 1,
 'upper left'   : 2,
 'lower left'   : 3,
 'lower right'  : 4,
 'right'        : 5,
 'center left'  : 6,
 'center right' : 7,
 'lower center' : 8,
 'upper center' : 9,
 'center'       : 10,

二、Annotation 標註

畫出基本圖

當圖線中某些特殊地方需要標註時,我們可以使用 annotation. matplotlib 中的 annotation 有兩種方法, 一種是用 plt 裏面的 annotate,一種是直接用 plt 裏面的 text 來寫標註.

首先,我們在座標軸中繪製一條直線.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 2*x + 1

plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)

Annotation 標註

移動座標

然後我們挪動座標軸的位置.

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

Annotation 標註

然後標註出點(x0, y0)的位置信息. 用plt.plot([x0, x0,], [0, y0,], ‘k–’, linewidth=2.5) 畫出一條垂直於x軸的虛線.

x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)
# set dot styles
plt.scatter([x0, ], [y0, ], s=50, color='b')

Annotation 標註

添加註釋 annotate

接下來我們就對(x0, y0)這個點進行標註.

plt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))

其中參數xycoords=‘data’ 是說基於數據的值來選位置, xytext=(+30, -30) 和 textcoords=‘offset points’ 對於標註位置的描述 和 xy 偏差值, arrowprops是對圖中箭頭類型的一些設置.

Annotation 標註

添加註釋 text

plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size': 16, 'color': 'r'})

其中-3.7, 3,是選取text的位置, 空格需要用到轉字符\ ,fontdict設置文本字體.

Annotation 標註

三、Tick 能見度

生成圖形

當圖片中的內容較多,相互遮蓋時,我們可以通過設置相關內容的透明度來使圖片更易於觀察,也即是通過本節中的bbox參數設置來調節圖像信息.

首先參考之前的例子, 我們先繪製圖像基本信息:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-3, 3, 50)
y = 0.1*x

plt.figure()
# 在 plt 2.0.2 或更高的版本中, 設置 zorder 給 plot 在 z 軸方向排序
plt.plot(x, y, linewidth=10, zorder=1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))

tick 能見度

調整座標

然後對被遮擋的圖像調節相關透明度,本例中設置 x軸 和 y軸 的刻度數字進行透明度設置

for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    # 在 plt 2.0.2 或更高的版本中, 設置 zorder 給 plot 在 z 軸方向排序
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
plt.show()

其中label.set_fontsize(12)重新調節字體大小,bbox設置目的內容的透明度相關參,facecolor調節 box 前景色,edgecolor 設置邊框, 本處設置邊框爲無,alpha設置透明度. 最終結果如下:

tick 能見度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章