Python數據可視化庫-Matplotlib(二)

咱們接着上次的繼續講解,先講一個概念,叫子圖的概念。dom

咱們先看一下這段代碼spa

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(3,2,1)
ax2 = fig.add_subplot(3,2,2)
ax3 = fig.add_subplot(3,2,3)
ax4 = fig.add_subplot(3,2,6)
plt.show()

咱們看到plt.figure()這個方法,咱們設置一個總體的圖。而後咱們在往這個圖中增長咱們須要的子圖3d

fig.add_subplot(3,2,1)意思是在figure中,添加一個3行2列的子圖,其中,最後一個參數是子圖的位置code

咱們在作一下變換,對比一下能夠很清楚的看到,咱們看看下面的代碼blog

import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(4,4,1)
ax2 = fig.add_subplot(4,4,2)
ax3 = fig.add_subplot(4,4,3)
ax4 = fig.add_subplot(4,4,4)
ax5 = fig.add_subplot(4,4,6)
ax6 = fig.add_subplot(4,4,7)
ax6 = fig.add_subplot(4,4,16)
plt.show()

能夠獲得以下的一個子圖it

import numpy as np
fig = plt.figure(figsize=(6,6))
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
ax1.plot(np.random.randint(1,5,5),np.arange(5))
ax2.plot(np.arange(10)*3,np.arange(10))
plt.show()

咱們能夠看到,咱們設置figsize=(6,6)咱們能夠圖的大小。設置兩個圖class

咱們在畫圖的時候,能夠直接經過ax1.plot,ax2.plot進行隨機數據配置import

unrate['MONTH'] = unrate['DATE'].dt.month
unrate['MONTH'] = unrate['DATE'].dt.month
fig = plt.figure(figsize=(6,3))

plt.plot(unrate[0:12]['MONTH'],unrate[0:12]['VALUE'],c ='red')
plt.plot(unrate[12:24]['MONTH'],unrate[12:24]['VALUE'],c ='blue')
plt.show()

 能夠看到咱們能夠設置折線圖的不一樣的顏色。隨機數

下面咱們看看這個例子配置

fig = plt.figure(figsize=(10,6))
colors = ['red','blue','green','orange','black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    plt.plot(subset['MONTH'],subset['VALUE'],c=colors[i])
plt.show()

咱們把數據經過不一樣的顏色的線條畫出來了,可是不知道每條線表明的是什麼意思。下面咱們給折線圖加上一個圖例:

fig = plt.figure(figsize=(10,6))
colors = ['red', 'blue', 'green', 'orange', 'black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    label = str(1948 + i)
    plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i], label=label)
plt.legend(loc='best')
plt.show()

 

咱們經過label=label 設置好一個label爲圖例,而後進行設置,默認爲plt.legend(loc='best')圖例顯示在右邊

咱們作下點單的修改,讓整個折線圖完整標準的顯示

fig = plt.figure(figsize=(10,6))
colors = ['red', 'blue', 'green', 'orange', 'black']
for i in range(5):
    start_index = i*12
    end_index = (i+1)*12
    subset = unrate[start_index:end_index]
    label = str(1948 + i)
    plt.plot(subset['MONTH'], subset['VALUE'], c=colors[i], label=label)
plt.legend(loc='upper left')
plt.xlabel('Month, Integer')
plt.ylabel('Unemployment Rate, Percent')
plt.title('Monthly Unemployment Trends, 1948-1952')
plt.show()

咱們增長了整個折線圖的XY軸表示,圖例位置調整爲左邊。添加了折線圖的標題。 

今天講解就先到這裏,咱們能夠看到,經過Matplotlib庫,能夠很輕鬆的畫出咱們想要的圖。

感謝各位的閱讀,謝謝~~

相關文章
相關標籤/搜索