1. 程式人生 > >python進階—matplotlib教程

python進階—matplotlib教程

簡介:matplotlib是python著名的繪相簿,它提供了一整套和matlab相似的API,十分適合互動式進行製圖。作為一套面向物件的會相簿,它所繪畫的圖表中的每個繪圖元素,都會在記憶體中有一個物件與之對應,我們只需要呼叫pyplot繪圖模組就能快速實現繪圖和設定圖表的各種細節。

1、簡單繪製(折線圖)

import matplotlib.pyplot as plt
import numpy as np

# 圖例、標題、標籤
x = [1, 2, 3]
y = [5, 7, 4]
x2 = [1, 2, 3]
y2 = [10, 14, 12]
# 生成線條,設定線條名稱
plt.plot(x, y, label="First Line")
plt.plot(x2, y2, label="Second Line")
# 給x,y軸建立標籤
plt.xlabel("Plot Number")
plt.ylabel("Important Var")
# 設定圖的標題
plt.title("Interesting Graph it out")
# 生成預設圖例
plt.legend()
plt.show()

2、繪製條形圖

plt.bar([1, 3, 5, 7, 9], [5, 2, 7, 8, 2], label="Example one")
# 建立條形圖,並設定條形圖顏色
plt.bar([2, 4, 6, 8, 10], [8, 6, 2, 5, 6], label="Example Two", color="r")
# 給x,y軸設定標籤
plt.xlabel("bar number")
plt.ylabel("bar height")
# 設定圖的標題
plt.title("Epic Graph Line")
# 生成預設圖例
plt.legend()
plt.show()

3、繪製直方圖

# 建立直方圖
ages = [22, 55, 62, 45, 21, 22, 34, 42, 42, 4, 99, 102, 110, 120, 121, 122, 130, 111, 115, 112, 80, 75, 65, 54, 44, 43,
        42, 48]
bins = np.linspace(0, 130, 14)
# histtype="bar":繪製條形圖,rwidth:設定條形圖的寬度
plt.hist(ages, bins, histtype="bar", rwidth=0.8)
plt.xlabel("x")
plt.ylabel("y")
plt.title("Interesting Graph")
plt.legend()
plt.show()

4、繪製散點圖

# 散點圖
x = np.arange(1, 8, 1)
y = np.array([5, 2, 4, 2, 1, 4, 5])
# color:顏色,s圖案大小,market:圖案型別
plt.scatter(x, y, label="skitscat", color="k", s=25, marker="o")
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.title("Interest Graph")
plt.show()

5、繪製堆疊圖

# 堆疊圖
days = [1, 2, 3, 4, 5]
sleeping = [7, 8, 6, 11, 7]
eating = [2, 3, 4, 3, 2]
working = [7, 8, 7, 2, 2]
playing = [8, 5, 7, 8, 13]
# 為了顯示圖例,建立每個圖例的樣式
plt.plot([], [], label="sleeping", color="m", linewidth=5)
plt.plot([], [], label="eating", color="c", linewidth=5)
plt.plot([], [], label="working", color="r", linewidth=5)
plt.plot([], [], label="playing", color="k", linewidth=5)
plt.stackplot(days, sleeping, eating, working, playing, colors=["m", "c", "r", "k"])
plt.xlabel("x")
plt.ylabel("y")
plt.title("Interesting Graph")
plt.legend()
plt.show()

6、繪製餅圖

# 建立餅圖
slices = [7, 2, 2, 13]
activities = ["sleeping", "eating", "working", "playing"]
cols = ["c", "m", "r", "b"]
# slices:切片資料,labels:標籤,colors:顏色,startangle:繪畫起始角度,shadow:新增陰影,explode:拉出一個切片,autopct:把百分比放在圖表上
plt.pie(slices, labels=activities, colors=cols, startangle=90, shadow=True, explode=(0, 0.1, 0, 0), autopct="%1.1f%%")
plt.title("Interesting Graph")
plt.show()

7、繪製