[Python] Python 學習 - 可視化資料操作(一)

來源:互聯網
上載者:User

標籤:cat   ext   att   continue   axis   values   logs   列表   機率   

Python 學習 - 可視化資料操作(一)

  GitHub:https://github.com/liqingwen2015/my_data_view

 

目錄
  • 折線圖
  • 散佈圖
  • 隨機漫步
  • 骰子點數機率
  • 檔案目錄

 

折線圖

  cube_squares.py

import matplotlib.pyplot as pltx_values=list(range(1, 5000))y_values=[pow(x, 3) for x in x_values]plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor=‘none‘, s=40)# 設定標題和樣式plt.title("Square Numbers", 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()

 

  mpl_squares.py

# 簡單的折線圖
import matplotlib.pyplot as pltinput_values=[1, 2, 3, 4, 5 ]squares = [1, 4, 9, 16, 25]# 繪製線條的粗細plt.plot(input_values, squares, linewidth=5)# 設定圖表標題,並給座標軸加上標籤plt.title("Square Numbers", fontsize=24)plt.xlabel("Value", fontsize=14)plt.ylabel("Square of Value", fontsize=14)# 設定刻度標記的大小,axis=‘both‘ 表示指定的實參影響 x 軸和 y 軸上的刻度plt.tick_params(axis=‘both‘, labelsize=14)plt.show()

 

散佈圖

  scatter_squares.py

# 散佈圖import matplotlib.pyplot as pltx_values = list(range(1, 1001))y_values = [x**2 for x in x_values]# c:顏色#plt.scatter(x_values, y_values, c=‘red‘, edgecolor=‘none‘, s=40)#plt.scatter(x_values, y_values, c=(0, 0, 8), edgecolor=‘none‘, s=40)plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues, edgecolor=‘none‘, s=40)# 設定標題和樣式plt.title("Square Numbers", 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()# 儲存圖表#plt.savefig(‘squared_plot.png‘, bbox_inches=‘tight‘)

 

隨機漫步

  random_walk.py

from random import choiceclass 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_step = self.get_step();            y_step = self.get_step();            # 拒絕原地踏步            if x_step == 0 and y_step == 0:                continue            # 計算下一個點的 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)    def get_step(self):        # 決定前進方向以及沿這個方向前進的距離        direction = choice([1, -1])  # 隨機選 1 或 -1        distance = choice([0, 1, 2, 3, 4])  # 隨機選 0, 1, 2, 3, 4        return direction * distance  # 正數:右移,負數:左移

   rw_visual.py

import matplotlib.pyplot as pltfrom 隨機漫步.random_walk import RandomWalkwhile True:    # 建立一個 RandomWalk 執行個體,並將其包含的點都繪製出來    rw = RandomWalk(5000)    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)    # 設定繪圖視窗的尺寸    #plt.figure(dpi=128, figsize=(10, 6))    # 突出起點和終點    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.plot(rw.x_values, rw.y_values, linewidth=10)    # 隱藏座標軸    plt.axes().get_xaxis().set_visible(False)    plt.axes().get_yaxis().set_visible(False)    plt.show()    keep_running = input("繼續?(y/n):")    if keep_running == ‘n‘:        break

 

 

骰子點數機率

  die.py

from random import randintclass Die():    # 表示一個骰子類    def __init__(self, num_sides=6):        # 6 面        self.num_sides = num_sides    def roll(self):        # 返回 1~6        return randint(1, self.num_sides)

  

  die_visual.py

import pygalfrom 骰子.die import Die# 建立一個 D6die = Die()results = []for roll_num in range(1000):    result = die.roll()    results.append(result)frequencies = []for value in range(1, die.num_sides+1):    # 計算某個值出現同樣的次數    frequency = results.count(value)    frequencies.append(frequency)# 對結果進行可視化hist = pygal.Bar()hist.title = "D6 1000次:"hist.x_labels = [str(num) for num in range(1, 7)] #[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘]hist.x_title = "結果"hist.y_title = "機率"hist.add(‘D6‘, frequencies)hist.render_to_file(‘images/die_visual.svg‘)

 

  dice_visual.py

import pygalfrom 骰子.die import Die# 建立 2 個 D6die_1 = Die()die_2 = Die()results = []for roll_num in range(1000):    result = die_1.roll() + die_2.roll()    results.append(result)frequencies = []max_results = die_1.num_sides + die_2.num_sidesfor value in range(2, max_results+1):    # 計算某個值出現同樣的次數    frequency = results.count(value)    frequencies.append(frequency)# 對結果進行可視化hist = pygal.Bar()hist.title = "D6 100次:"hist.x_labels = [str(num) for num in range(1, 13)] #[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘, ‘10‘, ‘11‘, ‘12‘]hist.x_title = "結果"hist.y_title = "出現的次數"hist.add(‘D6 + D6‘, frequencies)hist.render_to_file(‘images/dice_visual.svg‘)

 

  different_dice.py

import pygalfrom 骰子.die import Die# 建立一個 D6 和 D10die_1 = Die()die_2 = Die(10)results = []for roll_num in range(5000):    result = die_1.roll() + die_2.roll()    results.append(result)frequencies = []max_results = die_1.num_sides + die_2.num_sidesfor value in range(2, max_results+1):    # 計算某個值出現同樣的次數    frequency = results.count(value)    frequencies.append(frequency)# 對結果進行可視化hist = pygal.Bar()hist.title = "5000 次:D6 + D10 的結果。"hist.x_labels = [str(num) for num in range(2, 17)]hist.x_title = "結果"hist.y_title = "重複出現的次數"hist.add(‘D6 + D10‘, frequencies)hist.render_to_file(‘images/different_visual.svg‘)

 

檔案目錄

 

  GitHub:https://github.com/liqingwen2015/my_data_view

[Python] Python 學習 - 可視化資料操作(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.