第十五章 生成數(shù)據(jù)
一术唬、安裝matplotlib
1傍菇、在https://dev.windows.com下載Visual Studio Community讼载,并安裝
2趴荸、cmd進(jìn)入命令窗口儒溉,輸入:pip install matplotlib回車,進(jìn)入安裝
3发钝、驗證安裝結(jié)果
python
>>>import matplotlib
#沒報錯說明安裝成功
二顿涣、繪制圖表
繪制拆線圖
import matplotlib.pyplot as plt
input_values = [1,2,3,4,5,6]
squares = [1,2,4,9,16]
#根據(jù)squeres繪制圖形,linewidth線條加粗
plt.plot(input_values,squares,linewidth=5)
#設(shè)置標(biāo)題和標(biāo)題字號
plt.title("Squares",fontsize=24)
#x,y坐標(biāo)標(biāo)簽
plt.xlabel('Value')
plt.ylabel('squares of value')
plt.tick_params(axis='both', labelsize=14)
#打開matplotlib查看器
plt.show()
繪制拆散點圖
import matplotlib.pyplot as plt
values = list(range(1,1001))
squares = [x**2 for x in values]
#scatter:繪制點
#s=10:點的大小
#c='red'自定義顏色波闹,c=squeres,cmap=plt.cm.Blues漸變
#edgecolor='none':刪除數(shù)據(jù)點的廓
plt.scatter(values,squares,c=squares, cmap=plt.cm.Blues,edgecolor='none',s=10)
plt.title("Squares",fontsize=24)
plt.xlabel('Value')
plt.ylabel('squares of value')
#axis():指定每個坐標(biāo)的取值范圍,分別x和y坐標(biāo)最小值和最大值
plt.axis([0,1100,0,1100000])
#savefig():保存圖表涛碑,第一實參保存路徑和文件名精堕,
#第二個實參將圖表周圍多余的空白區(qū)域剪掉,如果要你保留可省略
plt.savefig('squares.png',bbox_inches='tight')
plt.show()
隨機(jī)漫步
import matplotlib.pyplot as plt
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)
while True:
rw = RandomWalk(5000)
rw.fill_walk()
#設(shè)置繪圖窗口尺寸
#figure()用于指定圖表的寬度蒲障、高度(單位英寸)歹篓、分辨率和背景色
plt.figure(figsize=(10,6))
num_points = list(range(rw.num_points))
plt.scatter(rw.x_values,rw.y_values,c=num_points,cmap=plt.cm.Blues,s=3)
#使用拆線圖繪制
#plt.plot(rw.x_values,rw.y_values,linewidth=5)
#繪制起點和終點
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)
#隱藏坐標(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
三、使用Pygal模擬擲骰子
Pygal(可視化包)生成可縮放的矢量圖形文件揉阎,可在不同尺寸的屏幕上自動縮放圖表
from random import randint
import pygal
class Die():
def __init__(self,num_sides = 6):
self.num_sides = 6
def roll(self):
return randint(1,self.num_sides)
die = Die()
results = []
#1000次投擲結(jié)果
for roll_num in range(1000):
result = die.roll()
results.append(result)
#分析每個點數(shù)出現(xiàn)次數(shù)
frequencies = []
for value in range(1,die.num_sides+1):
frequency = results.count(value)
frequencies.append(frequency)
print(frequencies)
#顯示直方圖
hist = pygal.Bar()
hist.title = 'Result of rolling one D6 1000 times'
hist.x_label = [1,2,3,4,5,6]
hist.x_title = 'result'
hist.y_title = 'Frequency of Result'
hist.add('D6',frequencies)
hist.render_to_file('die.svg')