2. Python數(shù)據(jù)可視化matplotlib.pyplot

1.生成數(shù)據(jù)

  1. 安裝matplotlib
# Mac
pip install --user matplotlib

在Python環(huán)境下,使用import matplotlib檢測(cè)是否安裝成功,不報(bào)錯(cuò)就是安裝成功

  1. 繪制簡(jiǎn)單圖形
import matplotlib.pyplot as plt

#圖形輸入值
input_values = [1,2,3,4,5]
#圖形輸出值
squares = [1,4,9,16,25]

#plot根據(jù)列表繪制出有意義的圖形,linewidth是圖形線寬,可省略
plt.plot(input_values,squares,linewidth=5)
#設(shè)置圖標(biāo)標(biāo)題
plt.title("Square Numbers",fontsize = 24)
#設(shè)置坐標(biāo)軸標(biāo)簽
plt.xlabel("Value",fontsize = 14)
plt.ylabel("Square of Value",fontsize = 14)
#設(shè)置刻度標(biāo)記的大小
plt.tick_params(axis='both',labelsize = 14)
#打開matplotlib查看器,并顯示繪制圖形
plt.show()
image

3.繪制點(diǎn)

import matplotlib.pyplot as plt

#繪制散點(diǎn)圖(傳如一對(duì)x和y坐標(biāo),在指定位置繪制一個(gè)點(diǎn))
plt.scatter(2,4)
#設(shè)置輸出樣式
plt.scatter(3,5,s=200)
plt.show()
image

4.繪制一系列的點(diǎn)

import matplotlib.pyplot as plt

x_values = [1,2,3,4,5]
y_values = [1,4,9,16,25]

plt.scatter(x_values,y_values,s=100)

plt.show()
image
  1. 自動(dòng)計(jì)算數(shù)據(jù)
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=100)

#設(shè)置每個(gè)坐標(biāo)軸的取值范圍(x軸取值,y軸取值)
plt.axis([0,1100,0,1100000])
plt.show()
image
  1. 刪除數(shù)據(jù)點(diǎn)的輪廓
import matplotlib.pyplot as plt

x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]

#matplotlib允許你給散點(diǎn)圖中的各個(gè)點(diǎn)指定顏色。默認(rèn)為藍(lán)色點(diǎn)和黑色輪廓,在散點(diǎn)圖包含的 數(shù)據(jù)點(diǎn)不多時(shí)效果很好。但繪制很多點(diǎn)時(shí),黑色輪廓可能會(huì)粘連在一起。
#edgecolor='none'刪除數(shù)據(jù)點(diǎn)的輪廓
plt.scatter(x_values,y_values,edgecolor='none', s=40)


#設(shè)置每個(gè)坐標(biāo)軸的取值范圍
plt.axis([0,1100,0,1100000])
plt.show()
image
  1. 自定義顏色c=''直接傳顏色或元組都可以
import matplotlib.pyplot as plt

x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]

#matplotlib允許你給散點(diǎn)圖中的各個(gè)點(diǎn)指定顏色。默認(rèn)為藍(lán)色點(diǎn)和黑色輪廓,在散點(diǎn)圖包含的 數(shù)據(jù)點(diǎn)不多時(shí)效果很好。但繪制很多點(diǎn)時(shí),黑色輪廓可能會(huì)粘連在一起。
#edgecolor='none'刪除數(shù)據(jù)點(diǎn)的輪廓
plt.scatter(x_values, y_values,c='red', edgecolor='none', s=40)
# plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolor='none', s=40)


#設(shè)置每個(gè)坐標(biāo)軸的取值范圍
plt.axis([0,1100,0,1100000])
plt.show()
image
  1. 使用顏色映射
import matplotlib.pyplot as plt

x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]

#matplotlib允許你給散點(diǎn)圖中的各個(gè)點(diǎn)指定顏色。默認(rèn)為藍(lán)色點(diǎn)和黑色輪廓,在散點(diǎn)圖包含的 數(shù)據(jù)點(diǎn)不多時(shí)效果很好。但繪制很多點(diǎn)時(shí),黑色輪廓可能會(huì)粘連在一起。
#edgecolor='none'刪除數(shù)據(jù)點(diǎn)的輪廓
plt.scatter(x_values, y_values,c=y_values,cmap=plt.cm.Blues, edgecolor='none', s=40)


#設(shè)置每個(gè)坐標(biāo)軸的取值范圍
plt.axis([0,1100,0,1100000])
plt.show()

將c設(shè)置成一個(gè)y值列表,并使用參數(shù)cmap告訴pyplot使用那個(gè)顏色映射,這些代碼將y值較小的點(diǎn)顯示為淺藍(lán)色,將y值較大的點(diǎn)顯示為深藍(lán)色


image
  1. 自動(dòng)保存圖表
import matplotlib.pyplot as plt

x_values = list(range(1,1001))
y_values = [x**2 for x in x_values]

#matplotlib允許你給散點(diǎn)圖中的各個(gè)點(diǎn)指定顏色。默認(rèn)為藍(lán)色點(diǎn)和黑色輪廓,在散點(diǎn)圖包含的 數(shù)據(jù)點(diǎn)不多時(shí)效果很好。但繪制很多點(diǎn)時(shí),黑色輪廓可能會(huì)粘連在一起。
#edgecolor='none'刪除數(shù)據(jù)點(diǎn)的輪廓
plt.scatter(x_values, y_values,c=y_values,cmap=plt.cm.Blues, edgecolor='none', s=40)


#設(shè)置每個(gè)坐標(biāo)軸的取值范圍
plt.axis([0,1100,0,1100000])
# plt.show()
#參數(shù)1指定要以什么樣的文件名保存圖表,保存和代碼的同目錄下,第二個(gè)參數(shù)表示要將多余的空白區(qū)域剪掉,要保留空白區(qū)域,可省略第二個(gè)參數(shù)
plt.savefig('squares_plot.png',bbox_inches='tight')
image
  1. 練習(xí)題
動(dòng)手試一試
15-1 立方:數(shù)字的三次方被稱為其立方。請(qǐng)繪制一個(gè)圖形,顯示前 5 個(gè)整數(shù)的立方 值,再繪制一個(gè)圖形,顯示前 5000 個(gè)整數(shù)的立方值。
15-2 彩色立方:給你前面繪制的立方圖指定顏色映射。
import matplotlib.pyplot as plt

# #圖形輸入值
# input_values = [1,2,3,4,5]
# #圖形輸出值
# square = [1,8,27,64,125]

# plt.scatter(input_values,square,linewidth = 5)

# plt.title("cube",fontsize = 24)
# plt.show()


input_values = list(range(0,5000))

square = [x**3 for x in input_values]

plt.scatter(input_values,square,c=input_values,cmap=plt.cm.Reds,edgecolor='none',s=40);
plt.show()
image
  1. 隨機(jī)漫步(繪制隨機(jī)漫步圖)
from random import choice

class RandomWalk(object):
    """一個(gè)生成隨機(jī)漫步數(shù)據(jù)的類"""
    def __init__(self, num_points = 5000):
        """初始化隨機(jī)漫步的屬性"""
        #存儲(chǔ)隨機(jī)漫步次數(shù)的變量
        self.num_points = num_points
        #所有隨機(jī)漫步都始于(0,0)
        #分別存儲(chǔ)隨機(jī)漫步經(jīng)過的每個(gè)點(diǎn)的x和y坐標(biāo)
        self.x_values = [0]
        self.y_values = [0]
        

    def fill_walk(self):
        """計(jì)算隨機(jī)漫步包含的所有點(diǎn)"""

        #不斷漫步,直到列表達(dá)到指定的長(zhǎng)度
        while len(self.x_values) < self.num_points:
            #決定前進(jìn)方向以及沿這個(gè)方向前進(jìn)的距離
            x_direction = choice([1,-1])
            x_distance = choice([0,1,2,3,4])
            x_step = x_direction * x_distance
            
            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

            #計(jì)算下一個(gè)點(diǎn)的x值和y值
            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)
        pass

繪制隨機(jī)漫步圖

import matplotlib.pyplot as plt

from random_walk import RandomWalk


#創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來

rw = RandomWalk()

rw.fill_walk()

plt.scatter(rw.x_values,rw.y_values,s=15)
plt.show()
image
  1. 模擬多次隨機(jī)漫步
import matplotlib.pyplot as plt

from random_walk import RandomWalk


#只要程序處于活動(dòng)狀態(tài),就不斷的模擬漫步

while True:
    #創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來
    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
  1. 給點(diǎn)著色
import matplotlib.pyplot as plt

from random_walk import RandomWalk


#只要程序處于活動(dòng)狀態(tài),就不斷的模擬漫步

while True:
    #創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來
    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,edgecolor='none',s=15)
    plt.show()
    
    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break

image
  1. 重新繪制起點(diǎn)和終點(diǎn)
import matplotlib.pyplot as plt

from random_walk import RandomWalk


#只要程序處于活動(dòng)狀態(tài),就不斷的模擬漫步

while True:
    #創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來
    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)
    
    #突出起點(diǎn)和終點(diǎn)
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)

    plt.show()

    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break

image
  1. 隱藏坐標(biāo)軸
while True:
    #創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來
    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)
    
    #突出起點(diǎn)和終點(diǎn)
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)

    #隱藏坐標(biāo)軸
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break
image
  1. 增加點(diǎn)數(shù)(增加點(diǎn)數(shù),將每個(gè)點(diǎn)的大小調(diào)?。?/li>
while True:
    #創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來
    rw = RandomWalk(50000)
    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=1)
    
    #突出起點(diǎn)和終點(diǎn)
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)

    #隱藏坐標(biāo)軸
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break
image

16.調(diào)整尺寸以適應(yīng)屏幕

while True:
    #創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來
    rw = RandomWalk(50000)
    rw.fill_walk()

    #設(shè)置繪圖窗口的尺寸
    #figure()用于指定圖表的寬度,高度,分辨率黑背景色figsize需要指定一個(gè)元組,單位英寸,dpi是分辨率,可傳可不傳
    plt.figure(dpi=128,figsize=(10,6))

    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=1)
    
    #突出起點(diǎn)和終點(diǎn)
    plt.scatter(0,0,c='green',edgecolor='none',s=100)
    plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)

    #隱藏坐標(biāo)軸
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break

  1. 練習(xí)1

    分子運(yùn)動(dòng):修改 rw_visual.py,將其中的 plt.scatter()替換為 plt.plot()。為 模擬花粉在水滴表面的運(yùn)動(dòng)路徑,向 plt.plot()傳遞 rw.x_values 和 rw.y_values,并 指定實(shí)參值 linewidth。使用 5000 個(gè)點(diǎn)而不是 50 000 個(gè)點(diǎn)。
while True:
    #創(chuàng)建一個(gè)RandomWalk實(shí)例,并將其包含的點(diǎn)都繪制出來
    rw = RandomWalk(5000)
    rw.fill_walk()

    #設(shè)置繪圖窗口的尺寸
    #figure()用于指定圖表的寬度,高度,分辨率黑背景色figsize需要指定一個(gè)元組,單位英寸,dpi是分辨率,可傳可不傳
    plt.figure(dpi=128,figsize=(10,6))

    point_numbers = list(range(rw.num_points))

    plt.plot(rw.x_values,rw.y_values,linewidth=1)
    # plt.scatter(rw.x_values,rw.y_values,c=point_numbers,cmap=plt.cm.Blues,edgecolors='none',s=1)
    
    #突出起點(diǎn)和終點(diǎn)
    # plt.scatter(0,0,c='green',edgecolor='none',s=100)
    # plt.scatter(rw.x_values[-1],rw.y_values[-1],c='red',edgecolors='none',s=100)

    #隱藏坐標(biāo)軸
    plt.axes().get_xaxis().set_visible(False)
    plt.axes().get_yaxis().set_visible(False)

    plt.show()

    keep_running = input("Make another walk?(y/n)")
    if keep_running=='n':
        break

image
  1. 練習(xí)2

    改進(jìn)的隨機(jī)漫步:在類 RandomWalk 中,x_step 和 y_step 是根據(jù)相同的條件生 8
    成的:從列表[1, -1]中隨機(jī)地選擇方向,并從列表[0, 1, 2, 3, 4]中隨機(jī)地選擇距離。 請(qǐng)修改這些列表中的值,看看對(duì)隨機(jī)漫步路徑有何影響。嘗試使用更長(zhǎng)的距離選擇列表, 如 0~8;或者將?1 從 x 或 y 方向列表中刪除。
    def fill_walk(self):
        """計(jì)算隨機(jī)漫步包含的所有點(diǎn)"""

        #不斷漫步,直到列表達(dá)到指定的長(zhǎng)度
        while len(self.x_values) < self.num_points:
            #決定前進(jìn)方向以及沿這個(gè)方向前進(jìn)的距離
            x_direction = choice([1])
            x_distance = choice([0,1,2,3,4,5,6,7,8])
            x_step = x_direction * x_distance
            
            y_direction = choice([1])
            y_distance = choice([0,1,2,3,4,5,6,7,8])
            y_step = y_direction * y_distance

            #拒絕原地踏步
            if x_step == 0 and y_step == 0:
                continue

            #計(jì)算下一個(gè)點(diǎn)的x值和y值
            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)
        pass
image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容