天天看點

【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

DataWhale學習位址:http://datawhale.club/t/topic/543

文字圖例盡眉目

  • Figure和Axes上的文本
    • test
    • title和set_title
    • figtext和text
    • suptitle
    • xlabel和ylabel
    • annotate
    • 字型的屬性設定
      • 以上學習内容分的總結案例
    • 數字表達式
  • Tick上的文本
    • 簡單模式
    • Tick Locators and Formatters
      • Tick Formatters
      • Tick Locators
  • legend(圖例)

Figure和Axes上的文本

Matplotlib具有廣泛的文本支援,包括對數學表達式的支援、對栅格和矢量輸出的TrueType支援、具有任意旋轉的換行分隔文本以及Unicode支援。

【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

test

pyplot API:

matplotlib.pyplot.text(x, y, s, fontdict=None, **kwargs)
OO API:Axes.text(self, x, y, s, fontdict=None, **kwargs)
           

參數:

  • s:此參數是要添加的文本。
  • xy:此參數是放置文本的點(x,y)。
  • fontdict:此參數是一個可選參數,并且是一個覆寫預設文本屬性的字典。如果fontdict為None,則由rcParams确定預設值。

傳回值:傳回作為建立的文本執行個體的文本

fontdict主要參數:

【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
import numpy as np
import matplotlib.pyplot as plt
#---------設定字型樣式,分别是字型,顔色,寬度,大小
font1 = {'family': 'Times New Roman',
        'color':  'purple',
        'weight': 'normal',
        'size': 16,
        }
font2 = {'family': 'Times New Roman',
        'color':  'red',
        'weight': 'normal',
        'size': 16,
        }
font3 = {'family': 'serif',
        'color':  'blue',
        'weight': 'bold',
        'size': 14,
        }
font4 = {'family': 'Calibri',
        'color':  'navy',
        'weight': 'normal',
        'size': 17,
        }
#-----------四種不同字型顯示風格-----
 
#-------建立函數----------
x = np.linspace(0.0, 5.0, 100)
y = np.cos(2*np.pi*x) * np.exp(-x/3)
#-------繪制圖像,添加标注----------
plt.plot(x, y, '--')
plt.title('Damped exponential decay', fontdict=font1)
#------添加文本在指定的坐标處------------
plt.text(2, 0.65, r'$\cos(2 \pi x) \exp(-x/3)$', fontdict=font2)
#---------設定坐标标簽
plt.xlabel('Y=time (s)', fontdict=font3)
plt.ylabel('X=voltage(mv)', fontdict=font4)
 
# 調整圖像邊距
plt.subplots_adjust(left=0.15)
plt.show()

           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

title和set_title

pyplot API:

matplotlib.pyplot.title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
OO API:Axes.set_title(self, label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs)
           

該指令是用來設定axes的标題。

參數:

  • label:str,此參數是要添加的文本
  • fontdict:dict,此參數是控制title文本的外觀,預設fontdict如下:
{'fontsize': rcParams['axes.titlesize'],
 'fontweight': rcParams['axes.titleweight'],
 'color': rcParams['axes.titlecolor'],
 'verticalalignment': 'baseline',
 'horizontalalignment': loc}
           
  • loc:str,{‘center’, ‘left’, ‘right’}預設為center
  • pad:float,該參數是名額題偏離圖表頂部的距離,預設為6。
  • y:float,該參數是title所在axes垂向的位置。預設值為1,即title位于axes的頂部。
  • kwargs:該參數是指可以設定的一些奇特文本的屬性。

    傳回值:

    傳回作為建立的title執行個體的文本

figtext和text

pyplot API:

matplotlib.pyplot.figtext(x, y, s, fontdict=None, **kwargs)
OO API:text(self, x, y, s, fontdict=None,**kwargs)
           

參數:

  • x,y:float,此參數是指在figure中放置文本的位置。一般取值是在[0,1]範圍内。使用transform關鍵字可以更改坐标系。
  • s:str,此參數是指文本
  • fontdict:dict,此參數是一個可選參數,并且是一個覆寫預設文本屬性的字典。如果fontdict為None,則由rcParams确定預設值。

傳回值:

傳回作為建立的文本執行個體的文本

suptitle

pyplot API:

matplotlib.pyplot.suptitle(t, **kwargs)
OO API:suptitle(self, t, **kwargs)
           

參數:

  • t: str,标題的文本
  • x:float,預設值是0.5.該參數是指文本在figure坐标系下的x坐标
  • y:float,預設值是0.95.該參數是指文本在figure坐标系下的y坐标
  • horizontalalignment, ha:該參數是指選擇文本水準對齊方式,有三種選擇{‘center’, ‘left’, right’},預設值是 ‘center’
  • verticalalignment, va:該參數是指選擇文本垂直對齊方式,有四種選擇{‘top’, ‘center’, ‘bottom’, ‘baseline’},預設值是 ‘top’
  • fontsize, size:該參數是指文本的大小,預設值是依據rcParams的設定:rcParams[“figure.titlesize”] (default: ‘large’)
  • fontweight, weight:該參數是用來設定字重。預設值是依據rcParams的設定:rcParams[“figure.titleweight”] (default: ‘normal’)
  • fontproperties:None or dict,該參數是可選參數,如果該參數被指定,字型的大小将從該參數的預設值中提取。

傳回:

傳回作為建立的title執行個體的文本

xlabel和ylabel

pyplot API:

matplotlib.pyplot.xlabel(xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
     matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None,*, loc=None, **kwargs)
OO API:  Axes.set_xlabel(self, xlabel, fontdict=None, labelpad=None, *, loc=None, **kwargs)
     Axes.set_ylabel(self, ylabel, fontdict=None, labelpad=None,*, loc=None, **kwargs)
           

參數:

  • xlabel或者ylabel:label的文本
  • labelpad:設定label距離軸(axis)的距離
  • loc:{‘left’, ‘center’, ‘right’},預設為center
  • **kwargs:文本屬性
#文本屬性的輸入一種是通過**kwargs屬性這種方式,一種是通過操作matplotlib.font_manager.FontProperties 方法
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import numpy as np

x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)

font = FontProperties()
font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('italic')

fig, ax = plt.subplots(figsize=(5, 3))
fig.subplots_adjust(bottom=0.15, left=0.2)
ax.plot(x1, y1)
ax.set_xlabel('time [s]', fontsize='large', fontweight='bold')
ax.set_ylabel('Damped oscillation [V]', fontproperties=font)

plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

annotate

pyplot API:

OO API:

參數:

  • text:str,該參數是指注釋文本的内容
  • xy:該參數接受二維元組(float, float),是指要注釋的點。其二維元組所在的坐标系xycoords參數決定
  • xytext:注釋文本的坐标點,也是二維元組,預設與xy相同
  • xycoords:該參數接受 被注釋點的坐标系屬性,允許的輸入值如下:
    【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
  • textcoords :注釋文本的坐标系屬性,預設與xycoords屬性值相同,也可設為不同的值。除了允許輸入xycoords的屬性值,還允許輸入以下兩種:
    【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
  • arrowprops:箭頭的樣式,dict(字典)型資料,如果該屬性非空,則會在注釋文本和被注釋點之間畫一個箭頭。如果不設定’arrowstyle’ 關鍵字,則允許包含以下關鍵字:
    【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
    如果設定了‘arrowstyle’關鍵字,以上關鍵字就不能使用。允許的值有:
    【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
    不同的arrowstytle的不同形式:
    【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
    FancyArrowPatch的關鍵字包括:
    【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
  • annotation_clip : 布爾值,可選參數,預設為空。設為True時,隻有被注釋點在axes時才繪制注釋;設為False時,無論被注釋點在哪裡都繪制注釋。僅當xycoords為‘data’時,預設值空相當于True。
  • **kwargs:該參數接受任何Text的參數
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig, axs = plt.subplots(2, 2)
x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7

ax = axs.flat[0]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)#在axes中建立一個artist
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="-",#箭頭的樣式
                            color="0.5",
                            patchB=None,
                            shrinkB=0,
                            connectionstyle="arc3,rad=0.3",
                            ),
            )
#在整個代碼中使用Transform=ax.transAx表示坐标相對于axes的bounding box,其中(0,0)是軸的左下角,(1,1)是右上角。
ax.text(.05, .95, "connect", transform=ax.transAxes, ha="left", va="top")

ax = axs.flat[1]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                            color="0.5",
                            patchB=el,#箭頭終點處的圖形
                            shrinkB=0,
                            connectionstyle="arc3,rad=0.3",
                            ),
            )
ax.text(.05, .95, "clip", transform=ax.transAxes, ha="left", va="top")

ax = axs.flat[2]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="-",
                            color="0.5",
                            patchB=el,
                            shrinkB=5,
                            connectionstyle="arc3,rad=0.3",
                            ),
            )
ax.text(.05, .95, "shrink", transform=ax.transAxes, ha="left", va="top")

ax = axs.flat[3]
ax.plot([x1, x2], [y1, y2], ".")
el = mpatches.Ellipse((x1, y1), 0.3, 0.4, angle=30, alpha=0.2)
ax.add_artist(el)
ax.annotate("",
            xy=(x1, y1), xycoords='data',
            xytext=(x2, y2), textcoords='data',
            arrowprops=dict(arrowstyle="fancy",
                            color="0.5",
                            patchB=el,
                            shrinkB=5,#箭頭終點的縮進點數
                            connectionstyle="arc3,rad=0.3",
                            ),
            )
ax.text(.05, .95, "mutate", transform=ax.transAxes, ha="left", va="top")

for ax in axs.flat:
    ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)

plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

兩個點之間的連接配接路徑主要有connectionstyle和以下樣式确定:

(其中angle3和arc3中的3意味着所得到的路徑是二次樣條段(三個控制點))

【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

展現了連接配接線的用法:

import matplotlib.pyplot as plt
def demo_con_style(ax, connectionstyle):
    x1, y1 = 0.3, 0.2
    x2, y2 = 0.8, 0.6

    ax.plot([x1, x2], [y1, y2], ".")
    ax.annotate("",
                xy=(x1, y1), xycoords='data',
                xytext=(x2, y2), textcoords='data',
                arrowprops=dict(arrowstyle="->", color="0.5",
                                shrinkA=5, shrinkB=5,
                                patchA=None, patchB=None,
                                connectionstyle=connectionstyle,
                                ),
                )

    ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
            transform=ax.transAxes, ha="left", va="top")


fig, axs = plt.subplots(3, 5, figsize=(8, 4.8))
demo_con_style(axs[0, 0], "angle3,angleA=90,angleB=0")
demo_con_style(axs[1, 0], "angle3,angleA=0,angleB=90")
demo_con_style(axs[0, 1], "arc3,rad=0.")
demo_con_style(axs[1, 1], "arc3,rad=0.3")
demo_con_style(axs[2, 1], "arc3,rad=-0.3")
demo_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0")
demo_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5")
demo_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5")
demo_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0")
demo_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5")
demo_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
demo_con_style(axs[0, 4], "bar,fraction=0.3")
demo_con_style(axs[1, 4], "bar,fraction=-0.3")
demo_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")

for ax in axs.flat:
    ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
fig.tight_layout(pad=0.2)

plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
#以下兩個block懂了之後,annotate基本懂了
#如果想更深入學習可以參看官網案例學習https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.annotate.html#matplotlib.axes.Axes.annotate
import numpy as np
import matplotlib.pyplot as plt
 
# 以步長0.005繪制一個曲線
x = np.arange(0, 10, 0.005)
y = np.exp(-x/2.) * np.sin(2*np.pi*x)
 
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xlim(0, 10)#設定x軸的範圍
ax.set_ylim(-1, 1)#設定x軸的範圍
 
# 被注釋點的資料軸坐标和所在的像素
xdata, ydata = 5, 0
xdisplay, ydisplay = ax.transData.transform_point((xdata, ydata))
 
# 設定注釋文本的樣式和箭頭的樣式
bbox = dict(boxstyle="round", fc="0.8")
arrowprops = dict(
    arrowstyle = "->",
    connectionstyle = "angle,angleA=0,angleB=90,rad=10")
 
# 設定偏移量
offset = 72
# xycoords預設為'data'資料軸坐标,對坐标點(5,0)添加注釋
# 注釋文本參考被注釋點設定偏移量,向左2*72points,向上72points
ax.annotate('data = (%.1f, %.1f)'%(xdata, ydata),
            (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',
            bbox=bbox, arrowprops=arrowprops)
 
# xycoords以繪圖區左下角為參考,機關為像素
# 注釋文本參考被注釋點設定偏移量,向右0.5*72points,向下72points
disp = ax.annotate('display = (%.1f, %.1f)'%(xdisplay, ydisplay),
            (xdisplay, ydisplay), xytext=(0.5*offset, -offset),
            xycoords='figure pixels',
            textcoords='offset points',
            bbox=bbox, arrowprops=arrowprops)
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
import numpy as np
import matplotlib.pyplot as plt
 
# 繪制一個極地坐标,再以0.001為步長,畫一條螺旋曲線
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
r = np.arange(0,1,0.001)
theta = 2 * 2*np.pi * r
line, = ax.plot(theta, r, color='#ee8d18', lw=3)
 
# 對索引為800處畫一個圓點,并做注釋
ind = 800
thisr, thistheta = r[ind], theta[ind]
ax.plot([thistheta], [thisr], 'o')
ax.annotate('a polar annotation',
            xy=(thistheta, thisr),  # 被注釋點遵循極坐标系,坐标為角度和半徑
            xytext=(0.05, 0.05),    # 注釋文本放在繪圖區的0.05百分比處
            textcoords='figure fraction',
            arrowprops=dict(facecolor='black', shrink=0.05),# 箭頭線為黑色,兩端縮進5%
            horizontalalignment='left',# 注釋文本的左端和低端對齊到指定位置
            verticalalignment='bottom',
            )
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

字型的屬性設定

一般有全局字型設定和自定義局部字型設定的兩種方法。

檢視matplotlib所有可用的字型:

from matplotlib import font_manager
font_family = font_manager.fontManager.ttflist
font_name_list = [i.name for i in font_family]
for font in font_name_list:
    print(f'{font}\n')
           

如何在matplotlib裡面,修改字型預設屬性,完成全局字型的更改:

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimSun']    # 指定預設字型為新宋體。
plt.rcParams['axes.unicode_minus'] = False      # 解決儲存圖像時 負号'-' 顯示為方塊和報錯的問題。
           
  • 局部字型修改方式1
#局部字型的修改方法1
import matplotlib.pyplot as plt
import matplotlib.font_manager as fontmg

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plt.plot(x, label='小示例圖示簽')

# 直接用字型的名字。
plt.xlabel('x 軸名稱參數', fontproperties='Microsoft YaHei', fontsize=16)         # 設定x軸名稱,采用微軟雅黑字型
plt.ylabel('y 軸名稱參數', fontproperties='Microsoft YaHei', fontsize=14)         # 設定Y軸名稱
plt.title('坐标系的标題',  fontproperties='Microsoft YaHei', fontsize=20)		  # 設定坐标系标題的字型
plt.legend(loc='lower right', prop={"family": 'Microsoft YaHei'}, fontsize=10)    # 小示例圖的字型設定
​
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
  • 局部字型修改方式2
#局部字型的修改方法2
import matplotlib.pyplot as plt
import matplotlib.font_manager as fontmg

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
plt.plot(x, label='小示例圖示簽')
#fname為你系統中的字型庫路徑
my_font1 = fontmg.FontProperties(fname=r'C:\Windows\Fonts\simhei.ttf')      # 讀取系統中的 黑體 字型。
my_font2 = fontmg.FontProperties(fname=r'C:\Windows\Fonts\simkai.ttf')      # 讀取系統中的 楷體 字型。
# fontproperties 設定中文顯示,fontsize 設定字型大小
plt.xlabel('x 軸名稱參數', fontproperties=my_font1, fontsize=16)       # 設定x軸名稱
plt.ylabel('y 軸名稱參數', fontproperties=my_font1, fontsize=14)       # 設定Y軸名稱
plt.title('坐标系的标題',  fontproperties=my_font2, fontsize=20)       # 标題的字型設定
plt.legend(loc='lower right', prop=my_font1, fontsize=10)              # 小示例圖的字型設定

plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

以上學習内容分的總結案例

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)

# Set titles for the figure and the subplot respectively
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
ax.set_title('axes title')

ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

# Set both x- and y-axis limits to [0, 10] instead of default [0, 1]
ax.axis([0, 10, 0, 10])

ax.text(3, 8, 'boxed italics text in data coords', style='italic',
        bbox={'facecolor': 'red', 'alpha': 0.5, 'pad': 10})

ax.text(2, 6, r'an equation: $E=mc^2$', fontsize=15)
font1 = {'family': 'Times New Roman',
        'color':  'purple',
        'weight': 'normal',
        'size': 10,
        }
ax.text(3, 2, 'unicode: Institut für Festkörperphysik',fontdict=font1)
ax.text(0.95, 0.01, 'colored text in axes coords',
        verticalalignment='bottom', horizontalalignment='right',
        transform=ax.transAxes,
        color='green', fontsize=15)

ax.plot([2], [1], 'o')
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
            arrowprops=dict(facecolor='black', shrink=0.05))

plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

數字表達式

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

plt.plot(t, s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$',
         fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

Tick上的文本

設定tick(刻度)和ticklabel(刻度标簽)也是可視化中經常需要操作的步驟,matplotlib既提供了自動生成刻度和刻度标簽的模式(預設狀态),同時也提供了許多讓使用者靈活設定的方式。

簡單模式

可以使用axis的set_ticks方法手動設定标簽位置,使用axis的set_ticklabels方法手動設定标簽格式。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib
x1 = np.linspace(0.0, 5.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
           

使用axis的set_ticks方法手動設定标簽位置:

# 使用axis的set_ticks方法手動設定标簽位置的例子,該案例中由于tick設定過大,是以會影響繪圖美觀,不建議用此方式進行設定tick
fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
axs[0].plot(x1, y1)
axs[1].plot(x1, y1)
axs[1].xaxis.set_ticks(np.arange(0., 10.1, 2.))
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

使用axis的set_ticklabels方法手動設定标簽格式:

fig, axs = plt.subplots(2, 1, figsize=(5, 3), tight_layout=True)
axs[0].plot(x1, y1)
axs[1].plot(x1, y1)
ticks = np.arange(0., 8.1, 2.)
tickla = [f'{tick:1.2f}' for tick in ticks]
axs[1].xaxis.set_ticks(ticks)
axs[1].xaxis.set_ticklabels(tickla)
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
#一般繪圖時會自動建立刻度,而如果通過上面的例子使用set_ticks建立刻度可能會導緻tick的範圍與所繪制圖形的範圍不一緻的問題。
#是以在下面的案例中,axs[1]中set_xtick的設定要與資料範圍所對應,然後再通過set_xticklabels設定刻度所對應的标簽
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(2, 1, figsize=(6, 4), tight_layout=True)
x1 = np.linspace(0.0, 6.0, 100)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
axs[0].plot(x1, y1)
axs[0].set_xticks([0,1,2,3,4,5,6])

axs[1].plot(x1, y1)
axs[1].set_xticks([0,1,2,3,4,5,6])#要将x軸的刻度放在資料範圍中的哪些位置
axs[1].set_xticklabels(['zero','one', 'two', 'three', 'four', 'five','six'],#設定刻度對應的标簽
                   rotation=30, fontsize='small')#rotation選項設定x刻度标簽傾斜30度。
axs[1].xaxis.set_ticks_position('bottom')#set_ticks_position()方法是用來設定刻度所在的位置,常用的參數有bottom、top、both、none
print(axs[1].xaxis.get_ticklines())
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

Tick Locators and Formatters

可以使用Tick Locators and Formatters完成對于刻度位置和刻度标簽的設定。

其中Axis.set_major_locator和Axis.set_minor_locator方法用來設定标簽的位置,Axis.set_major_formatter和Axis.set_minor_formatter方法用來設定标簽的格式。這種方式的好處是不用顯式地列舉出刻度值清單。

set_major_formatter和set_minor_formatter這兩個formatter格式指令可以接收字元串格式(matplotlib.ticker.StrMethodFormatter)或函數參數(matplotlib.ticker.FuncFormatter)來設定刻度值的格式 。

Tick Formatters

接收字元串格式的例子:

fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
for n, ax in enumerate(axs.flat):
    ax.plot(x1*10., y1)

formatter = matplotlib.ticker.FormatStrFormatter('%1.1f')
axs[0, 1].xaxis.set_major_formatter(formatter)

formatter = matplotlib.ticker.FormatStrFormatter('-%1.1f')
axs[1, 0].xaxis.set_major_formatter(formatter)

formatter = matplotlib.ticker.FormatStrFormatter('%1.5f')
axs[1, 1].xaxis.set_major_formatter(formatter)

plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

接收函數的例子:

def formatoddticks(x, pos):
    """Format odd tick positions."""
    if x % 2:
        return f'{x:1.2f}'
    else:
        return ''

fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
ax.plot(x1, y1)
ax.xaxis.set_major_formatter(formatoddticks)
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

Tick Locators

在普通的繪圖中,我們可以直接通過上圖的set_ticks進行設定刻度的位置,缺點是需要自己指定或者接受matplotlib預設給定的刻度。當需要更改刻度的位置時,matplotlib給了常用的幾種locator的類型。如果要繪制更複雜的圖,可以先設定locator的類型,然後通過axs.xaxis.set_major_locator(locator)繪制即可。

locator=plt.MaxNLocator(nbins=7)
locator=plt.FixedLocator(locs=[0,0.5,1.5,2.5,3.5,4.5,5.5,6])#直接指定刻度所在的位置
locator=plt.AutoLocator()#自動配置設定刻度值的位置
locator=plt.IndexLocator(offset=0.5, base=1)#面元間距是1,從0.5開始
locator=plt.MultipleLocator(1.5)#将刻度的标簽設定為1.5的倍數
locator=plt.LinearLocator(numticks=5)#線性劃分5等分,4個刻度
           
# 接收各種locator的例子
fig, axs = plt.subplots(2, 2, figsize=(8, 5), tight_layout=True)
for n, ax in enumerate(axs.flat):
    ax.plot(x1*10., y1)

locator = matplotlib.ticker.AutoLocator()
axs[0, 0].xaxis.set_major_locator(locator)

locator = matplotlib.ticker.MaxNLocator(nbins=10)
axs[0, 1].xaxis.set_major_locator(locator)


locator = matplotlib.ticker.MultipleLocator(5)
axs[1, 0].xaxis.set_major_locator(locator)


locator = matplotlib.ticker.FixedLocator([0,7,14,21,28])
axs[1, 1].xaxis.set_major_locator(locator)

plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

matplotlib.dates 子產品還提供了特殊的設定日期型刻度格式和位置的方式:

import matplotlib.dates as mdates
import datetime
# 特殊的日期型locator和formatter
locator = mdates.DayLocator(bymonthday=[1,15,25])
formatter = mdates.DateFormatter('%b %d')

fig, ax = plt.subplots(figsize=(5, 3), tight_layout=True)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
base = datetime.datetime(2017, 1, 1, 0, 0, 1)
time = [base + datetime.timedelta(days=x) for x in range(len(x1))]
ax.plot(time, y1)
ax.tick_params(axis='x', rotation=70)
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本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()
plt.plot(x,y2)
plt.plot(x,y1,color='red',linewidth=1.0,linestyle = '--')
plt.xlim((-3,5))
plt.ylim((-3,5))
plt.xlabel('x')
plt.ylabel('y')
new_ticks1 = np.linspace(-3,5,5)
plt.xticks(new_ticks1)
plt.yticks([-2,0,2,5],[r'$one\ shu$',r'$\alpha$',r'$three$',r'four'])
'''
上一行代碼是将y軸上的小标改成文字,其中,空格需要增加\,即'\ ',$可将格式更改成數字模式,如果需要輸入數學形式的α,則需要用\轉換,即\alpha
如果使用面向對象的指令進行畫圖,那麼下面兩行代碼可以實作與 plt.yticks([-2,0,2,5],[r'$one\ shu$',r'$\alpha$',r'$three$',r'four']) 同樣的功能
axs.set_yticks([-2,0,2,5])
axs.set_yticklabels([r'$one\ shu$',r'$\alpha$',r'$three$',r'four'])
'''
ax = plt.gca()#gca = 'get current axes' 擷取現在的軸
'''
ax = plt.gca()是擷取目前的axes,其中gca代表的是get current axes。
fig=plt.gcf是擷取目前的figure,其中gcf代表的是get current figure。

許多函數都是對目前的Figure或Axes對象進行處理,
例如plt.plot()實際上會通過plt.gca()獲得目前的Axes對象ax,然後再調用ax.plot()方法實作真正的繪圖。

而在本例中則可以通過ax.spines方法獲得目前頂部和右邊的軸并将其顔色設定為不可見
然後将左邊軸和底部的軸所在的位置重新設定
最後再通過set_ticks_position方法設定ticks在x軸或y軸的位置,本示例中因所設定的bottom和left是ticks在x軸或y軸的預設值,是以這兩行的代碼也可以不寫
'''
ax.spines['top'].set_color('none')
ax.spines['right'].set_color('none')
ax.spines['left'].set_position(('data',0))
ax.spines['bottom'].set_position(('data',0))#axes 百分比
ax.xaxis.set_ticks_position('bottom')   #設定ticks在x軸的位置
ax.yaxis.set_ticks_position('left')     #設定ticks在y軸的位置
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

legend(圖例)

圖例設定中的常見術語:

【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

右側的方框中的共有兩個legend entry;兩個legend key,分别是一個藍色和一個黃色的legend key;兩個legend label,一個名為‘Line up’和一個名為‘Line Down’的legend label:

【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

方法接受的參數:

【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

常用的幾個參數:

  • 設定圖例位置
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)
  • 設定圖例字型大小
  • 設定圖例邊框及背景
plt.legend(loc=‘best’,frameon=False) #去掉圖例邊框
plt.legend(loc=‘best’,edgecolor=‘blue’) #設定圖例邊框顔色
plt.legend(loc=‘best’,facecolor=‘blue’) #設定圖例背景顔色,若無邊框,參數無效
           
  • 設定圖例标題
  • 設定圖例名字及對應關系
line_up, = plt.plot([1, 2, 3], label='Line 2')
line_down, = plt.plot([3, 2, 1], label='Line 1')
plt.legend([line_up, line_down], ['Line Up', 'Line Down'],loc=5, title='line',frameon=False)#loc參數設定圖例所在的位置,title設定圖例的标題,frameon參數将圖例邊框給去掉
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)

顯示多圖例legend:

import matplotlib.pyplot as plt
import numpy as np
x = np.random.uniform(-1, 1, 4)
y = np.random.uniform(-1, 1, 4)
p1, = plt.plot([1,2,3])
p2, = plt.plot([3,2,1])
l1 = plt.legend([p2, p1], ["line 2", "line 1"], loc='upper left')
 
p3 = plt.scatter(x[0:2], y[0:2], marker = 'D', color='r')
p4 = plt.scatter(x[2:], y[2:], marker = 'D', color='g')
# 下面這行代碼由于添加了新的legend,是以會将l1從legend中給移除
plt.legend([p3, p4], ['label', 'label1'], loc='lower right', scatterpoints=1)
# 為了保留之前的l1這個legend,是以必須要通過plt.gca()獲得目前的axes,然後将l1作為單獨的artist
plt.gca().add_artist(l1)
plt.show()
           
【DataWhale資料可視化學習】文字圖例盡眉目Figure和Axes上的文本Tick上的文本legend(圖例)