python資料視覺化
- 使用scatter()繪製一系列點
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.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.tick_params(axis='both', which='major', labelsize=14)
plt.show()
- 自動計算資料
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.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=14)
plt.ylabel("Square of Value", fontsize=14)
plt.axis([0, 1100, 0, 1100000])
plt.show()
- 刪除資料點的輪廓
plt.scatter(x_values, y_values, edgecolors='none', s=40)
- 自定義顏色
plt.scatter(x_values, y_values, c='red', edgecolors='none', s=40)
還可以使用RGB顏色模式自定義顏色。 例如,下面的程式碼建立一個由淡藍色組成的散點圖:
plt.scatter(x_values, y_values, c=(0, 0, 0.8), edgecolors='none', s=40)
- 使用顏色對映
顏色對映(colormap)時一些列顏色,用於突出資料的規律。
plt.scatter(x_values, y_values, c=y_values, cmap=plt.cm.Blues,
edgecolors='none', s=40)
- 自動儲存圖片
plt.savefig('squares_plot.png', bbox_inches='tight')
第一個實參表示檔名,第二個實參指定將圖表多餘的空白區域裁剪掉。
- 隨機漫步
plot.py
from random import choice
class RandomWalk():
def __init__(self, num_points=5000):
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
while len(self.x_values) < self.num_points:
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
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_visual.py
import matplotlib.pyplot as plt
from plot import RandomWalk
#建立一個RandomWalk例項,並將其包含的點都繪製出來
rw = RandomWalk()
rw.fill_walk()
plt.scatter(rw.x_values, rw.y_values, s=15)
plt.show()
- 模擬多次隨機漫步
import matplotlib.pyplot as plt
from plot import RandomWalk
#建立一個RandomWalk例項,並將其包含的點都繪製出來
while True:
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
- 設定隨機漫步圖的樣式
-
- 給點著色
plt.scatter(rw.x_values, rw.y_values, c=point_numbers,
cmap=plt.cm.Blues, edgecolor='none', s=15)
-
- 重新繪製起點和終點
著色:指出它們的先後順序
還可以讓起點和終點變得更大,並顯示為不同的顏色。
plt.scatter(rw.x_values, rw.y_values, c=point_numbers,
cmap=plt.cm.Blues, edgecolor='none', s=15)
plt.scatter(0, 0, c='green', edgecolor='none', s=100)
plt.scatter(rw.x_values[-1], rw.y_values[-1], c='red',
edgecolor='none', s=100)
-
- 隱藏座標軸
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)