數據可視化(一)-Matplotlib簡易入門


本節的內容來源:https://www.dataquest.io/mission/10/plotting-basics

本節的數據來源:https://archive.ics.uci.edu/ml/datasets/Forest+Fires

原始數據展示(這張表記錄了某個公園的火災情況,X和Y代表的是坐標位置,area代表的是燒毀面積)

import pandas

forest_fires = pandas.read_csv('forest_fires.csv')

print(forest_fires.head(5))

Image 001

 

在使用matplotlib庫的時候,都會默認地縮寫為plt

import matplotlib.pyplot as plt

一個作圖的過程分為三步:

1.初始化繪圖數據

2.作圖

3.展示該圖

 

散點圖

使用matplotlib.pyplot.scatter()方法來做散點圖,第一個參數作為x軸,第二參數作為y軸,注意兩個參數都只能是列表數據或者Series

# 使用列表數據作為坐標軸

import matplotlib.pyplot as plt

weight = [600,150,200,300,200,100,125,180]

height = [60,65,73,70,65,58,66,67]

plt.scatter(height, weight)

plt.show()

Image 003

# 使用Series作為坐標軸

#以風速數據(wind)作為x軸,燒毀面積(area)作為y軸,做出它們的散點圖

plt.scatter(forest_fires["wind"], forest_fires["area"])

plt.show()

Image 002

可以留意到上面的兩張圖都沒有圖標題,也沒有橫坐標和縱坐標的文字說明,可以通過幾個函數來添加相應的信息:

  • title() -- 添加圖的表題
  • xlabel() -- 添加x軸的文字說明信息
  • ylabel() -- 添加y軸的文字說明信息
plt.scatter(forest_fires['wind'], forest_fires['area'])

plt.title('Wind speed vs fire area')

plt.xlabel('Wind speed when fire started')

plt.ylabel('Area consumed by fire')

plt.show()

Image 004

 

折線圖

折線圖使用matplotlib.pyplot.plot()函數來作圖,參數的要求和上面的散點圖一樣,下面只舉一個例子即可

# 使用列表數據作為坐標軸

age = [5, 10, 15, 20, 25, 30]

height = [25, 45, 65, 75, 75, 75]

plt.plot(age, height)

plt.title('Age vs Height')

plt.xlabel('age')

plt.ylabel('Height')

plt.show()

Image 005

 

條形圖

使用matplotlib.pyplot.bar()函數來繪制垂直型的條形圖,參數要求同上,下面只舉一個例子

# 現在要按月份統計燒毀的面積

# 先做一個透視圖,計算每個月的燒毀面積

area_by_month = forest_fires.pivot_table(index="month", values="area", aggfunc=numpy.sum)

Image 008

plt.bar(range(len(area_by_month)), area_by_month)

plt.title('Month vs Area')

plt.xlabel('month')

plt.ylabel('area')

plt.show()

Image 010

一定要注意,上圖中的X軸對應數字並不代表月份,因為area_by_month中的數據是無序的

 

使用matplotlib.pyplot.barh()函數來繪制水平型的條形圖,注意:與bar()函數最大的不同是X軸和Y軸是顛倒過來的

plt.barh(range(len(area_by_month)), area_by_month)

plt.title('Month vs Area')

plt.xlabel('area')

plt.ylabel('month')

plt.show()

Image 011

可以看到X軸與Y軸是顛倒過來的

 

使用不同的作圖主題

可以選擇使用不同的作圖主題,使用style.use()函數即可

# 使用兩種主題做一下對比

plt.style.use('fivethirtyeight')

plt.plot(forest_fires['rain'], forest_fires['area'])

plt.show()

Image 012

plt.style.use('ggplot')

plt.plot(forest_fires['rain'], forest_fires['area'])

plt.show()

Image 013

通常使用以下幾種主題:

fivethirtyeight,ggplot,dark_background,bmh


免責聲明!

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



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