數據可視化(一):matplotlib

1. matplotlib簡介

Matplotlib是一個Python 2D繪圖庫,能夠生成各類硬拷貝格式和跨平臺交互式環境的出版物質量數據。Matplotlib可用於Python腳本,Python和IPython shell,Jupyter筆記本,Web應用程序服務器和四個圖形用戶界面工具包。shell

2. matplotlib安裝

matplotlib安裝可使用源碼安裝和pip安裝。pip安裝方式以下:服務器

pip install matplotlib

默認安裝最新版本,也能夠安裝指定版本dom

pip install matplotlib==2.2.0

3. matplotlib繪圖實例

3.1 匯制常見統計學圖形

  • 散點圖
x = np.arange(50)
y = x + 5 * np.random.rand(50)
plt.scatter(x, y)
plt.title('散點圖')                             # 添加標題
plt.xlabel('自變量')                         # 添加橫座標
plt.ylabel('因變量')                         # 添加縱座標
plt.xlim(xmin=0, xmax=50)            # 添加橫座標範圍 
plt.ylim(ymin=0, ymax=50)            # 添加縱座標範圍

數據可視化(一):matplotlib

  • 直方圖ide

    plt.hist(x=np.random.randn(100), bins=10, color='b', alpha=0.3)

    數據可視化(一):matplotlib

  • 折線圖函數

    plt.plot([1,2,3,4,5],[1,4,5,2,7])

    數據可視化(一):matplotlib

  • 柱狀圖工具

    x = np.arange(5)
    y1, y2 = np.random.randint(1, 25, size=(2, 5))
    width = 0.25
    plt.bar(x, y1, width, color='r')
    plt.bar(x+width, y2, width, color='g')

    數據可視化(一):matplotlib

  • 餅圖
explode=(0,0.1,0,0,0)
partions = [0.30,0.20,0.1,0.15,0.25]
labels = ['蘋果','三星','小米','華爲','others']
plt.pie(partions,labels=labels,explode=explode,autopct='%1.0f%%')

數據可視化(一):matplotlib

3.2 匯制數學函數曲線

  • 三角函數spa

    x = np.arange(-np.pi,np.pi,0.01)
    y1 = np.sin(x)
    y2 = np.cos(x)
    plt.plot(x,y1,color='green',linewidth=1,linestyle='-',label='正弦曲線')
    plt.plot(x,y2,color='blue',linewidth=1,linestyle='--',label='餘弦曲線')
    plt.legend()   # 添加標註

    數據可視化(一):matplotlib

  • 指數函數code

    t = np.linspace(-50.0,50.0,1000)
    func_exp = np.exp(-0.1*t)
    plt.plot(t,func_exp)
    plt.title('exp(-0.1*t)')

    數據可視化(一):matplotlib

  • 對數函數
    t = np.linspace(-10.0,10.0,1000)
    func_log2 = np.log2(t)
    plt.plot(t,func_log2)
    plt.title('log2(t)')
    plt.grid()

    數據可視化(一):matplotlib

相關文章
相關標籤/搜索