Matplotlib 圖例

Matplotlib 原生支援圖例。圖例可以放置在不同的位置:圖例可以放在圖表的內部或外部,並且可以移動位置。

legend() 方法將圖例新增到圖中。在本文中,我們將向你展示使用 Matplotlib 的一些圖例。

Matplotlib 內部圖例

要將圖例放在裡面,只需呼叫 legend()

import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend()
plt.show()

![Matplotlib](/img/Tutorial/Matplotlib/Matplotlib legend.svg)

Matplotlib 底部圖例

要將圖例放在底部,請將 legend() 呼叫更改為:

ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),  shadow=True, ncol=2)

ncol=2 將列數設定為 2 列,shadow=True 設定圖例會有陰影。

完整的程式碼是:

import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), shadow=True, ncol=2)
plt.show()

![圖例放在底部](/img/Tutorial/Matplotlib/Matplotlib legend bottom.svg)

Matplotlib 的頂部圖例

要將圖例置於頂部,請更改 bbox\_to\_anchor 值:

ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00),  shadow=True, ncol=2)

程式碼如下:

import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00), shadow=True, ncol=2)
plt.show()

![圖例在上面](/img/Tutorial/Matplotlib/Matplotlib legend top inside.svg)

Matplotlib 圖例放右側外部

我們可以通過調整框的大小來設定圖例,並將圖例放在圖的右側外部,

chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)

程式碼:

import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend outside')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
plt.show()

![Matplotlib 放外面的圖例](/img/Tutorial/Matplotlib/Matplotlib legend right outside.svg)