Matplotlib數據可視化(4):折線圖與散點圖


In [1]:
from matplotlib import pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']  # 中文字體支持
 

對於折線圖的繪制,在之前博客的示例中都有使用,在面向對象繪圖方法中,一般是創建axes實例后調用plot()方法實現折線圖繪制,並通過傳遞各種參數實現對圖像的設置。 散點圖的繪制通過axes實例的scatter()方法來實現。scatter()方法的參數和參數取值與繪制折線圖的plot()方法基本一致,所以本文將兩種圖放在一起進行介紹。

 

1 多圖像繪制

 

在一個axes中,可以繪制多條折線圖,秩序多次調用plot()或者scatter()方法即可。

In [2]:
x1 = np.linspace(0.0, 5.0, 10)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axes = plt.subplots(1, 2, figsize=(10, 3), tight_layout=True)

# 折線圖
axes[0].set_title('圖1 折 線 圖')
axes[0].plot(x1, y1)
axes[0].plot(x1, y1+0.5)

# 散點圖
axes[1].set_title('圖2 散 點 圖')
axes[1].scatter(x1, y1)
axes[1].scatter(x1, y1+0.5)
plt.show()
 
 

2 顏色

 

顏色通過color參數來設置,color參數的值可以使顏色的英文全稱,例如'green'、'red',也可以是簡寫,例如'g'表示'green'、'r表示'red',一些常見顏色全稱和簡寫如下所示。

  • 'b' , blue
  • 'g' , green
  • 'r' , red
  • 'c' , cyan
  • 'm' , magenta
  • 'y' , yellow
  • 'k' , black
  • 'w' , white

如果覺得這些常見的顏色不夠用,設置可以用16進制字符來表示顏色。

In [3]:
x1 = np.linspace(0.0, 5.0, 10)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axes = plt.subplots(1, 2, figsize=(10, 3), tight_layout=True)

# 折線圖
axes[0].set_title('圖1 折 線 圖')
axes[0].plot(x1, y1, color='red')  # 紅色
axes[0].plot(x1, y1+0.5, color='g')  # 綠色
axes[0].plot(x1, y1+1, color='#008000')  # 也是綠色

# 散點圖
axes[1].set_title('圖2 散 點 圖')
axes[1].scatter(x1, y1, color='red')  # 紅色
axes[1].scatter(x1, y1+0.5, color='g')  # 綠色
axes[1].scatter(x1, y1+1, color='#008000')  # 也是綠色
plt.show()
 
 

3 圖例

 

axes實例中提供了legend()方法用於添加圖例,legend()方法會將元素的label字符串設置為圖例,如下面的示例所示,有兩種參數傳遞方式來設置label。除了label外,還可以傳遞loc參數來設置圖例的位置,loc參數值可以使代表位置的字符串,也可以是對應的整數,其對應關系如下所示:

    ===============   =============
    Location String   Location Code
    ===============   =============
    '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
    ===============   =============
In [4]:
x1 = np.linspace(0.0, 5.0, 10)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axes = plt.subplots(3, 2, figsize=(10, 8), tight_layout=True)

axes[0, 0].plot(x1, y1, label='線1')  # 傳遞label參數
axes[0, 0].plot(x1, y1+0.5, label='線2')  # 傳遞label參數
axes[0, 0].legend(loc='best')  # 默認就是best

axes[1, 0].plot(x1, y1, label='線1')  # 傳遞label參數
axes[1, 0].plot(x1, y1+0.5, label='線2')  # 傳遞label參數
axes[1, 0].legend(loc='lower right')

line1, = axes[2, 0].plot(x1, y1)  # 注意,等號前面有逗號
line2, = axes[2, 0].plot(x1, y1+0.5)
axes[2, 0].legend(handles=(line1, line2), labels=('線1', '線2'), loc='upper center')


axes[0, 1].scatter(x1, y1, label='第一組')  # 傳遞label參數
axes[0, 1].scatter(x1, y1+0.5, label='第二組')  # 傳遞label參數
axes[0, 1].legend(loc='best')  # 默認就是best

axes[1, 1].scatter(x1, y1, label='第一組')  # 傳遞label參數
axes[1, 1].scatter(x1, y1+0.5, label='第二組')  # 傳遞label參數
axes[1, 1].legend(loc='lower right')


group1 = axes[2, 1].scatter(x1, y1)   # 注意,等號前面沒有逗號,這是與plot()方法不同的
group2 = axes[2, 1].scatter(x1, y1+0.5) 

axes[2, 1].legend(handles=(group1, group2), labels=('第一組', '第二組'), loc='upper center')

plt.show()
 
 

4 線型

 

通過傳遞linestyle或ls參數可以設置線型,參數包含一下幾種取值:

    =============    ===============================
    character        description
    =============    ===============================
    ``'-'``          實線(默認)
    ``'--'``         長虛線
    ``'-.'``         點划線
    ``':'``          虛線
    =============    ===============================
In [5]:
x1 = np.linspace(0.0, 5.0, 10)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x1, y1, color='black', label='-', ls='-')  # 默認線性就是'-'
axes.plot(x1, y1+0.5, color='green', label='--',ls='--')
axes.plot(x1, y1+1, color='blue',  label='-.', linestyle='-.')
axes.plot(x1, y1+1.5, color='red', label=':', ls=':')
axes.legend()
plt.show()
 
 

5 標記(形狀)

 

參數marker可以在圖形中添加標記,標記參數值和對應的標記類型如下所示:

 
    =============    ===============================
    character        description
    =============    ===============================
    ``'.'``          點
    ``','``          像素點
    ``'o'``          圓
    ``'v'``          向下三角形
    ``'^'``          向上三角形
    ``'<'``          向左三角形
    ``'>'``          向右三角形
    ``'1'``          向下T形
    ``'2'``          向上T形
    ``'3'``          向左T形
    ``'4'``          向右T形
    ``'s'``          正方形
    ``'p'``          五邊形
    ``'*'``          星型
    ``'h'``          六邊形1
    ``'H'``          六邊形2
    ``'+'``          十字形
    ``'x'``          x 形
    ``'D'``          大菱形
    ``'d'``          小菱形
    ``'|'``          豎線
    ``'_'``          橫線
    =============    ===============================
In [6]:
x1 = np.linspace(0.0, 5.0, 10)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig, axes = plt.subplots(1, 2, figsize=(10, 3), tight_layout=True)

axes[0].plot(x1, y1, color='black', label='.', marker='.') 
axes[0].plot(x1, y1+0.5, color='green', label=',', marker=',')
axes[0].plot(x1, y1+1, color='blue',  label='o', marker='|')
axes[0].plot(x1, y1+1.5, color='red', label='v', marker='_')
axes[0].legend()

axes[1].scatter(x1, y1, color='black', label='.', marker='.') 
axes[1].scatter(x1, y1+0.5, color='green', label=',', marker=',')
axes[1].scatter(x1, y1+1, color='blue',  label='o', marker='|')
axes[1].scatter(x1, y1+1.5, color='red', label='v', marker='_')
axes[1].legend()
plt.show()
 
 

繪制折線圖時,在傳遞了marker參數后,也可以通過以下參數進一步設置標記的樣式:

  • markeredgecolor 或 mec : 邊框顏色
  • markeredgewidth 或 mew : 邊框粗細
  • markerfacecolor 或 mfc :填充色
  • markersize 或 ms :大小
In [7]:
x1 = np.linspace(0.0, 5.0, 10)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.plot(x1, y1, color='blue', label='線1', marker='*',markersize=15, markerfacecolor='green',markeredgecolor='red', markeredgewidth=3) # 線1
axes.plot(x1, y1+0.5, color='blue', label='線2', marker='*',markersize=15, markerfacecolor='green',markeredgecolor='red')   # 線2
axes.plot(x1, y1+1, color='blue', label='線3', marker='*',markersize=5, markerfacecolor='red')   # 線3
axes.plot(x1, y1+1.5, color='blue', label='線4',marker='*',markersize=10, markerfacecolor='red')   # 線4
axes.legend()
plt.show()
 
 

散點圖修改點的樣式時,參數與折線圖有些許不同:

  • s : 大小
  • color 或 c : 填充色
  • alpha:透明度
  • linewidths:邊框粗細
  • edgecolors:邊框顏色
In [8]:
x1 = np.linspace(0.0, 5.0, 10)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
fig = plt.figure()
axes = fig.add_subplot(1, 1, 1)
axes.scatter(x1, y1, color='green', label='第一組', marker='*',s=105,edgecolors='red', linewidths=5)
axes.scatter(x1, y1+0.5, color='green', label='第二組', marker='*',s=15)
axes.scatter(x1, y1+1, color='blue', label='第三組', marker='*',s=5)
axes.scatter(x1, y1+1.5, color='blue', label='第四組',marker='*',s=10)
axes.legend()
plt.show()
 
 

6 顯示坐標

 

顯示坐標可以用添加text的方法實現:

In [9]:
x1 = [i*0.1 for i in range(0, 50, 5)]
y1 = [i*i for i in x1]
fig, axes = plt.subplots(1, 2, figsize=(10, 3), tight_layout=True)

axes[0].plot(x1, y1, color='red', label='.', marker='.')  # 默認線性就是'-'
axes[1].scatter(x1, y1, color='blue', label='.', marker='*')  # 默認線性就是'-'
for a, b in zip(x1, y1):  
    axes[0].text(a, b, (a,b),ha='left', va='top', fontsize=10) 
    axes[1].text(a, b, (a,b),ha='left', va='top', fontsize=10)
plt.show()
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM