Python資料視覺化matplotlib庫

zoukeqing發表於2019-03-04

開始

每次建立檔案加上,避免中文亂碼問題

# -*-coding:utf-8-*-
複製程式碼

如果還遇到中文亂碼問題可在Python檔案程式碼上右鍵選擇File Encoding,並選擇UTF-8編碼格式

matplotlib : matplotlib.org/

matplotlib各種示例畫廊,單擊圖示即可檢視用於生成圖表的程式碼

繪製圖之前注意安裝matplotlib

pip install matplotlib
複製程式碼

pip安裝包加速器國內映象,命令新增-i引數

pip install matplotlib -i https://pypi.tuna.tsinghua.edu.cn/simple
複製程式碼

繪製簡單的折線圖

示例

import matplotlib.pyplot as plt

squares = [1, 2, 4, 5, 8]
plt.plot(squares)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

修改標籤文字和線條粗細

import matplotlib.pyplot as plt

squares = [1, 2, 4, 5, 8]
plt.plot(squares)
# 設定圖示標題,並給座標軸加上標籤
plt.title("Hello Squares", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 設定刻度標記的大小
plt.tick_params(axis='both',labelsize=14)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫
校正圖形

仔細觀察橫座標發現座標的點是從零開始的

import matplotlib.pyplot as plt

squares = [1, 2, 4, 5, 8]
input_value = [1, 2, 3, 4, 5]
plt.plot(input_value, squares, linewidth=5)
# 設定圖示標題,並給座標軸加上標籤
plt.title("Hello Squares", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 設定刻度標記的大小
plt.tick_params(axis='both',labelsize=14)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

繪製散點圖

使用scatter()繪製散點圖並設定其樣式

繪製單個點

import matplotlib.pyplot as plt
#
plt.scatter(5, 8)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

新增樣式,使其更加有趣

import matplotlib.pyplot as plt
import matplotlib as mpl

# 解決中文亂碼問題
# sans-serif就是無襯線字型,是一種通用字型族。
# 常見的無襯線字型有 Trebuchet MS, Tahoma, Verdana, Arial, Helvetica, 中文的幼圓、隸書等等。
# 指定預設字型 SimHei為黑體
mpl.rcParams['font.sans-serif'] = ['SimHei']
# 用來正常顯示負號
mpl.rcParams['axes.unicode_minus'] = False
plt.scatter(-5, 8, s=200)
# 設定圖表標題並給座標軸加上標籤
plt.title(u"單點散點圖", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
# 設定刻度標記的大小
plt.tick_params(axis='both', which='major', labelsize=14)

plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

繪製一系列點

import matplotlib.pyplot as plt
#
x_value = [1, 2, 3, 4, 5]
y_value = [1, 2, 4, 5, 8]
plt.scatter(x_value, y_value, s=100)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

自動計算資料

import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x ** 2 for x in x_values]
plt.scatter(x_values, y_values, s=40)
# 設定每個座標軸的取值範圍
plt.axis([0, 1100, 0, 1100000])
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

刪除資料點的輪廓

plt.scatter(x_values, y_values, s=40, edgecolors='none')
複製程式碼

自定義顏色

plt.scatter(x_values, y_values, s=40, edgecolors='none', c='yellow')
plt.scatter(x_values, y_values, s=40, edgecolors='none', c=(0, 0.8, 0.8))
複製程式碼

使用顏色對映

顏色對映是一系列顏色,從起始顏色漸變到結束顏色

plt.scatter(x_values, y_values, s=40, edgecolors='none', c=y_values, cmap=plt.cm.Blues)
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

自動儲存圖示

import matplotlib.pyplot as plt

x_values = list(range(1, 1001))
y_values = [x ** 2 for x in x_values]
plt.scatter(x_values, y_values, s=40)
# 設定每個座標軸的取值範圍
plt.axis([0, 1100, 0, 1100000])
bbox_inches='tight' 指定將圖表多餘的空白區域裁剪掉
# 如果要保留圖表周圍多餘的空白區域,可省略bbox_inches實參
plt.savefig('save_plot.png', bbox_inches='tight')
複製程式碼

隨機漫步

什麼是隨機漫步?類似水滴中的分子運動,分子受到擠壓而產生運動

建立RandomWalk() 類

from random import choice
import matplotlib.pyplot as plt


class RandomWalk:
    """生成隨機漫步的類"""
    def __init__(self, num_points=5000):
        """初始化隨機漫步的屬性"""
        self.num_points = num_points
        # 所有隨機漫步都始於(0,0)
        self.x_values = [0]
        self.y_values = [0]

    def fill_walk(self):
        """計算隨機漫步包含的所有點"""
        # 生成漫步包含的點,並決定每次漫步的方向
        # 不斷漫步,也就是遍歷列表
        while len(self.x_values) < self.num_points:
            # 給x_direction 選擇一個值,結果要麼是表示向右走的1,要麼是表示向左走的-1
            x_direction = choice([-1, 1])
            # 隨機地選擇一個0~4之間的整數,決定走多遠
            x_distance = choice([0, 1, 2, 3, 4])
            # 將移動方向乘以移動距離,確定沿 x 和 y 軸移動的距離
            # x_step 為正,將向右移動,為負將向左移動,而為零將垂直移動
            x_step = x_direction * x_distance
            # y軸也類似
            y_direction = choice([-1, 1])
            y_distance = choice([0, 1, 2, 3, 4])
            y_step = y_direction * y_distance
            # 拒絕原地踏步
            if x_step == 0 and y_step ==0:
                continue
            # 計算下一個點的x和y值,-1指示列表最後一個數
            next_x = self.x_values[-1] + x_step
            next_y = self.y_values[-1] + y_step
            # 附加到列表末尾
            self.x_values.append(next_x)
            self.y_values.append(next_y)
複製程式碼
  • 簡單繪製隨機漫步圖
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

  • 模擬多次隨機漫步
while True:
    建立一個RandomWalk例項,並將其包含的點都繪製出來
    rw = RandomWalk()
    rw.fill_walk()
    plt.scatter(rw.x_values, rw.y_values, s=15)
    plt.show()
    keep_running = input("Make another walk? (y/n): ")
    if keep_running == 'n':
        break
複製程式碼
  • 設定隨機漫步圖的樣式——著色
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.prism, edgecolors='none', s=15)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

  • 繪製起點和終點
rw = RandomWalk()
rw.fill_walk()
point_numbers = list(range(rw.num_points))
plt.scatter(rw.x_values, rw.y_values, c=point_numbers, cmap=plt.cm.Blues, edgecolors='none', s=15)
plt.scatter(0, 0, c='green', edgecolors='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red', edgecolors='none', s=100)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

  • 隱藏座標軸
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

  • 增加點數
rw = RandomWalk(10000)
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, edgecolors='none', s=15)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

  • 調整尺寸以適合螢幕
rw = RandomWalk()
rw.fill_walk()
plt.figure(figsize=(10, 6))
# 1000 * 600畫素
plt.scatter(rw.x_values, rw.y_values, edgecolors='none', s=15)
plt.show()
複製程式碼

效果如下:

Python資料視覺化matplotlib庫

matplotlib其它圖形庫可參考 : matplotlib.org/api/_as_gen…

繪相簿除了matplotlib,還有pygal、ggplot、plotly等等

相關文章